Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c - Printing binary number giving weird results

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

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

1 Reply

0 votes
by (71.8m points)

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('
');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...