编译器C++如何在二进制代码中表示整数
How does C++ compiler represent int numbers in binary code?
我编写了一个程序,它使用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
- 您可能更喜欢CHAR_BIT宏而不是原始 8 (
#include <climits>
(。 - 考虑您的起始值!假设
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
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 我无法找到这些代码段的大 O 表示法
- 表示行为与复制代码块的函数参数?
- 编译器C++如何在二进制代码中表示整数
- 此代码的 Big-O 表示法是什么?
- 计算代码块的 O 表示法
- 表示分割故障的代码
- 这段代码的 Big-O 表示法是什么
- 以图形方式表示C++代码
- 用十六进制表示法编写代码有什么意义
- 将c代码的中间表示分解回c
- 移植将 32 位浮点数与使用 64 位进行比较的代码,此值表示什么
- //![0]表示在Qt c++中的示例代码
- 如何从g++生成的目标代码中去掉表示源头文件的绝对路径的字符串
- 如何将c++代码包装成具有大量浮点*(表示点)的CLI
- 以0符号表示的运行时代码
- 执行时,1D Peak表示错误导致代码停止工作