# Thread: preceding zeros in int variables

1. ## preceding zeros in int variables

I have to write a program that reads a decimal integer (int) entered in binary form and converts it into its decimal equivalent. I've got the program up and running except for one thing: any zeros I enter before a 1 are discounted, ie. 0001 = 1 as far as the computer is concerned. Is there any way I can get around this? Here's my code:

-----

/* Converts a binary number to its decimal equivalent */

#include <stdio.h>

int main()
{
int num, Num, NUM, digit, decimal = 0, count = 1, ten = 10;

printf( "Please enter a number in binary form: " );
scanf( "%d", &num );
Num = num;
NUM = num;

while ( num > 0 )
{
while ( Num > ten )
Num /= 10;

digit = Num % 10;
num /= 10;
decimal += digit * count;
count *= 2;
ten *= 10;
Num = NUM;
}

printf( "\n\n\nThe decimal equivalent of %d is %d.", NUM, decimal );

return 0;
}

-----

Thanks gang!

Ash

2. > Is there any way I can get around this?
Yes - read the user input into an array of characters.

If you assume that the user typed in a binary string, then you might have something like
if ( buff[i] == '1' ) {
// a 1 bit
} else {
// a 0 bit
}

3. curse you and your super-moderated speed, salem! you stole my answer