Thread: Converting decimal to binary?

  1. #1
    Unregistered
    Guest

    Converting decimal to binary?

    Is there an easy way to convert a decimal number to binary in C? For example, how could I go from:

    decimal 3 to binary 0011?

    Thanks for any advice.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Yup. The easiest way is to use the search button. Alternately, if you actually want to learn what you're doing, rather than taking someone's example, you could go here.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    0011 =


    0 * 2^3 +
    0 * 2^2 +
    1 * 2^1 +
    1 * 2^0 =
    3

    is bit even? if no, 1. if yes, 0
    divide by 2 (or bit shift)
    is bit even? if no, 1. if yes, 0
    etc... for 7 more times

  4. #4
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    Code:
    void displayBits( unsigned value )
    { 
       unsigned c, displayMask = 1 << 31;
    
       printf( "%7u = ", value );
    
       for ( c = 1; c <= 32; c++ ) { 
          putchar( value & displayMask ? '1' : '0' );
    
          value <<= 1;
    
          if ( c % 8 == 0 )
             putchar( ' ' );
       }
    
       putchar( '\n' );
    }

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 decimal to binary within a I/O program
    By RandomX in forum C Programming
    Replies: 4
    Last Post: 11-26-2006, 09:25 AM
  3. Replies: 9
    Last Post: 10-07-2006, 05:37 AM
  4. 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
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM