打印二进制数给人怪异的结果 [英] Printing binary number giving weird results

查看:163
本文介绍了打印二进制数给人怪异的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查位运算符,并写了一个简单的code打印数字的二进制重新presentation但我有疯狂输出,而我自己也没有解释。为什么程序没有给我正确的二进制数?
下面是输出示例:

和我的code:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;无效pBinary(INT X);INT主要(无效)
{
    对于(INT N = 0; N< 20; N ++){
        pBinary(N);
    }
    返回0;
}无效pBinary(INT X)
{
    INT Y = 1<< 31;
    对于(INT N = 0; N< 32; N ++){
        X'放大器; ÿ?的putchar('1'):的putchar('0');
        Y'GT;> = 1;
    }
    的putchar('\\ n');
}


解决方案

如果 INT 是32位长, 1<< 31 可调用符号整数溢出,这是的未定义行为

考虑为对付无符号的价值。

 无效pBinary(unsigned int类型X)
{
    unsigned int类型Y = 1U<< 31;
    对于(INT N = 0; N< 32; N ++){
        X'放大器; ÿ?的putchar('1'):的putchar('0');
        Y'GT;> = 1;
    }
    的putchar('\\ n');
}

这是使用更安全类型的定义大小。包括 inttypes.h stdint.h 使用 uint32_t的

 无效pBinary(uint32_t的X)
{
    uint32_t的= UINT32_C(1) - ;&下; 31;
    对于(INT N = 0; N< 32; N ++){
        X'放大器; ÿ?的putchar('1'):的putchar('0');
        Y'GT;> = 1;
    }
    的putchar('\\ n');
}

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 :

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

解决方案

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

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

这篇关于打印二进制数给人怪异的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆