Thread: Converting Integers to Binary

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Cshot's code does not appear to be correct.
    Code:
    #include <stdio.h>
    
    int main()
    {
       int i;
       int value = 125;
    
       for(i = 0; i < sizeof(int)*8; i++)
          printf("%d", (value >> (sizeof(int)*8 /* - 1 */ - i)) & 1);
       printf("\n");
       return 0;
    }
    
    /* my output
    10000000000000000000000000111110
    */
    I would like to point out that a char does not necessarily contain 8 bits, so the 8 is not very portable.

    Also, an integer /may/ include padding bits, so using sizeof(int) * CHAR_BIT is not even fully portable.

    Using unsigned types would be preferable when using bit shifts.

    And as an individual preference, I like to do sizeof(value) instead of sizeof(int) -- I try to avoid the middleman of assuming the underlying type.
    Last edited by Dave_Sinkula; 10-03-2002 at 12:32 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting 32 bit binary IP to decimal IP (vice-versa)
    By Mankthetank19 in forum C Programming
    Replies: 15
    Last Post: 12-28-2009, 07:17 PM
  2. Converting From Binary Tree to Threaded Binary Trees
    By elton_fan in forum C Programming
    Replies: 15
    Last Post: 11-08-2007, 11:41 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Converting Sign Magnitude Integer Binary Files
    By Arthur Dent in forum C Programming
    Replies: 7
    Last Post: 09-13-2004, 10:07 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM