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?
You're creating a binary string of 33 digits, not 32:
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
Assuming an int
is 32 bits wide, on the last iteration of the loop you shift by an amount that is the same size as the variable you're shifting. Doing so invokes undefined behavior. This is documented in section 6.5.7p3 of the C standard regarding the bitwise shift operators:
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
Change the stopping point of the loop to 32, and adjust the subtractions and setting of the null terminating byte accordingly.
void Convert_Number_To_Binary(const int num,char *binary) {
//Start from binary[0] and check if num is divisible by 2^ith power by shifting
for(int i = 0; i < 32; 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] = '1';
}
else
binary[32-i-1] = '0';
//printf("i:%d, 32-i-1:%d\n", i, (32-i-1));
}
//printf("%c, %c", binary[0], binary[31]);
binary[32] = '\0';
}