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.

Printable View

- 04-16-2002UnregisteredConverting 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. - 04-16-2002quzah
- 04-16-2002ygfperson
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 - 04-17-2002NutshellCode:
`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' );

}