I'm writing a function to print the Binary Representation of an integer which is 4-Bytes on my machine.
I'm creating a mask = 0x80000000
which should be
( 10000000 00000000 00000000 00000000 )
and creating a loop to shift this mask right and making and
operation and if it is one I'll print 1 else I'll print 0, but I'm getting wrong results!
For example: for decimal 10 I'm getting 00000000 00000000 00000000 00001111
.
#include <stdio.h>
void Binary( int ) ;
int main()
{
Binary(10) ; // 00000000 00000000 00000000 00001111
while(1);
return 0;
}
void Binary( int num )
{
int mask = 0x80000000 ;
for(int i = 0 ; i<32; i++)
{
if( (mask>>i)&num )
{
printf("1") ;
}
else
{
printf("0") ;
}
}
}
When you shift the int right, it fills with the sign bit because it is signed. So 0x80000000 >> 1 is 0xc0000000; >> 2 is 0xe0000000; >> 23 is 0xffffffff; >> 31 is 0xffffffff.
The value 10 is binary 1010, so it and to non-zero for every i in 28,29,30,31. You can test this by modifying your program to try some different numbers:
4: 00000000000000000000000000000111
8: 00000000000000000000000000000111
15:00000000000000000000000000001111
16:00000000000000000000000000011111
As the comments mention, if you switch to unsigned, this will not happen.
ps: It is entirely possible that signed shifting has been redefined to be undefined behaviour, in which case you are lucky your house didn’t burn down.
User contributions licensed under CC BY-SA 3.0