0

I'm trying to print a number in binary with these two approaches:

Approach 1:

int input;
scanf("%d", &input);

for(int i = sizeof(int)*CHAR_BIT - 1; i >= 0; i--)
printf("%u",(input & (1<<i)) >> i);

Approach 2:

int input;
scanf("%d", &input);

for(int i = sizeof(int)*CHAR_BIT - 1; i >= 0; i--)
(input & (1<<i)) ? putchar('1') : putchar('0');

Approach 2 works fine but in Approach 1 the first "digit" that is printed is 4294967295 and I can't find the error.

Kona98
  • 139
  • 2
  • 9

3 Answers3

2

It doesn't make sense to use signed numbers for bit shifts. When you shift data into the sign bit of the int, you invoke undefined behavior. Also be aware that the 1 literal is of type int.

Solve this by using unsigned types and get rid of the na(t)ive C types at the same time, in favour for stdint.h.

uint32_t input = 0x88776655;

for(uint32_t i=0; i<32; i++)
{
  printf("%u", (input & (1u<<31-i)) >> 31-i);
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
0

use unsigned type and watch out the i>=0 comparison. because unsigned type always >=0. it cannot be minus.

unsigned int input;
scanf("%u", &input);
for(unsigned int i = sizeof(int)*8 - 1; ; i--) {
    printf("%u",(input & (1u<<i)) >> i);
    if ( i==0 ) break ;
}
printf("\n") ;
Junhee Shin
  • 748
  • 6
  • 8
  • This code also invokes undefined behavior, just like the original code. Namely when `i` is 31 and you do `1< – Lundin Mar 19 '18 at 10:38
0

Solve this by casting to unsigned type before working with bits.

printf("%u", ((unsigned int)input & (1 << i)) >> i);
  • `1 << i` with `i==31` _still_ invokes undefined behavior. This is the 4th time in this thread that I point this out. – Lundin Mar 19 '18 at 13:55