[英]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;
}
結果:
#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-- ; ) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.