Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was reviewing bitwise operators and wrote a simple code to print the binary representation of numbers but I am having crazy output, and I have no explanation for it. why is the program not giving me the correct binary numbers ? Here is the sample output :enter image description here

and my code :

#include <stdio.h>
#include <stdlib.h>

void pBinary(int x);

int main(void)
{
    for (int n = 0; n < 20; n++) {
        pBinary(n);
    }
    return 0;
}

void pBinary(int x)
{
    int y = 1 << 31;
    for (int n = 0; n < 32; n++) {
        x & y ? putchar('1') : putchar('0');
        y >>= 1;
    }
    putchar('
');
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

If int is 32-bit long, 1 << 31 invokes signed integer overflow, which is undefined behavior.

Consider making the value to deal with unsigned.

void pBinary(unsigned int x)
{
    unsigned int y = 1u << 31;
    for (int n = 0; n < 32; n++) {
        x & y ? putchar('1') : putchar('0');
        y >>= 1;
    }
    putchar('
');
}

It is safer to use types with defined size. Include inttypes.h or stdint.h to use uint32_t.

void pBinary(uint32_t x)
{
    uint32_t = UINT32_C(1) << 31;
    for (int n = 0; n < 32; n++) {
        x & y ? putchar('1') : putchar('0');
        y >>= 1;
    }
    putchar('
');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...