编译器C++如何在二进制代码中表示整数

How does C++ compiler represent int numbers in binary code?

本文关键字:代码 表示 整数 二进制 C++ 编译器      更新时间:2023-10-16

我编写了一个程序,它使用C++中的按位运算符显示特定整数值的二进制表示。对于偶数,它按我的预期工作,但对于奇数,它在二进制表示的左侧添加 1。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    unsigned int a = 128;
    for (int i = sizeof(a) * 8; i >= 0; --i) {
        if (a & (1UL << i)) { // if i-th digit is 1
            cout << 1;        // Output 1
        }
        else {
            cout << 0;        // Otherwise output 0
        }
    }
    cout << endl;
    system("pause");
    return 0;
}

结果:

  • 对于 a = 128: 000000000000000000000000010000000,
  • 对于 a = 127:100000000000000000000000001111111
  1. 您可能更喜欢CHAR_BIT宏而不是原始 8 (#include <climits> (。
  2. 考虑您的起始值!假设unsigned int有 32 位,您的起始值是 int i = 4*8 ,因此1U << i将值移出范围。这是未定义的行为,可能会导致任何事情,显然,您的特定编译器硬件%32移位,因此您得到一个初始value & 1,导致意外的前导 1...您是否注意到您实际上打印了 33 位数字而不是仅打印了 32 位数字?

问题就在这里:

for (int i = sizeof(a) * 8; i >= 0; --i) {

它应该是:

for (int i = sizeof(a) * 8; i-- ; ) {

http://coliru.stacked-crooked.com/a/8cb2b745063883fa