Im currently writing a C function that takes a number from the user and converts it into a binary output. First, here's the code:
void Convert_Number_To_Binary(const int num,char *binary) {
double remainder = num;
//Start from binary[0] and check if num is divisible by 2^ith power by shifting
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
printf("i: %d, %d \n", i, (shift) );
//If shift is greater than 0, then remainder is divisible by 2^i
if( (shift & 1) > 0) {
binary[32-i] = '1';
}
else
binary[32-i] = '0';
//printf("i:%d, 32-i:%d\n", i, (32-i));
}
//printf("%c, %c", binary[0], binary[31]);
binary[33] = '\0';
}
The code works fine for the most part, except when I enter an odd number (ex: 17), I get a one in the most siginifanct position:
num = 17 binary = 100000000000000000000000000010001
The leading "1" doesn't appear for a even number:
num = 16 binary = 000000000000000000000000000010000
I am running this on a remote 32-bit linux machine, could that be the reason?