Why am I getting a wrong binary pattern?

0

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") ;
        }
    }
}
c
bit-manipulation
asked on Stack Overflow Jul 11, 2019 by mrMatrix • edited Jul 11, 2019 by 89f3a1c

1 Answer

1

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.

answered on Stack Overflow Jul 11, 2019 by mevets

User contributions licensed under CC BY-SA 3.0