![](/img/trans.png)
[英]C++ - Copying unsigned char* to a new unsigned char* array
[英]C++ copying integer to char[] or unsigned char[] error
因此,我正在使用以下代碼將整數放入char []或無符號char []中
(unsigned???) char test[12];
test[0] = (i >> 24) & 0xFF;
test[1] = (i >> 16) & 0xFF;
test[2] = (i >> 8) & 0xFF;
test[3] = (i >> 0) & 0xFF;
int j = test[3] + (test[2] << 8) + (test[1] << 16) + (test[0] << 24);
printf("Its value is...... %d", j);
當我使用無符號字符類型和值1000000000時,它可以正確打印。
當我使用char類型(相同的值)時,會得到98315724的打印內容嗎?
所以,問題是,真的有人可以解釋到底發生了什么嗎?
在檢查了兩個不同數字的二進制文件后,我仍然無法弄清楚到底發生了什么。 我認為帶符號的是當MSB設置為1來指示負值時(但是負char?wth?)。
我明確告訴緩沖區要插入什么內容,以及如何解釋內容,所以不明白為什么會發生這種情況。
為了清楚起見,我在下面包括了二進制/十六進制。
11 1010 1001 1001 1100 1010 0000 0000 //二進制為983157248
11 1011 1001 1010 1100 1010 0000 0000 // 1000000000的二進制
3 A 9 9 CA 0 0 //十六進制為983157248
3 B 9 ACA 0 0 //十六進制為1000000000
當你說i & 0xFF
等等,你在范圍creaing值[0, 256)
但是,(您的) char
的范圍為[-128, +128)
,因此您實際上不能明智地存儲這些值(即,行為是實現定義的,並且難以理解)。
使用unsigned char
作為無符號值。 線索就是名字。
除了Kerrek SB的答案以外,請考慮以下事項:
計算機(幾乎總是)對負數使用稱為二進制補碼的表示法 ,其中高位用作“負”指示符。 問自己,考慮到計算機將專門處理帶符號位,對帶符號類型執行移位時會發生什么。
您可能需要閱讀為什么當左側操作數的值為負時,為什么左移操作會調用Undefined Behavior? 就在StackOverflow上獲得提示。
所有這些都與internal representation
以及每種type
使用該data
解釋它的方式有關。 在帶signed character
的internal representation
中,字節的第一位保留符號,其余部分保留值。 當第一位為1時,數字為負,隨后的位代表正值的complement
。 例如:
unsigned char c; // whose internal representation we will set at 1100 1011
c = (1 * 2^8) + (1 * 2^7) + (1 * 2^4) + (1 * 2^2) + (1 * 2^1);
cout << c; // will give 203
// inversely:
char d = c; // not unsigned
cout << d; // will print -53
// as if the first is 1, d is negative,
// and other bits complement of value its positive value
// 1100 1011 -> -(complement of 100 1011)
// the complement is an XOR +1 011 0101
// furthermore:
char e; // whose internal representation we will set at 011 0101
e = (1 * 2^6) + (1 * 2^5) + (1 * 3^2) + (1 * 2^1);
cout << e; // will print 53
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.