我想我的问题归结为: 为什么
char
和 unsigned Char
即使在位操作上也有不同的对待?
它们大小相同,看起来也一样
找到这个 但对我来说,它并不能解释为什么它在位操作级别上应该有不同的操作
我从文件中读取了两个字节。 这些必须组合成一个
16 bit
数字。
我用 bit shifting <<
和 logical or |
.
uint16_t universe = (hb << 8) | lb;
我认为代码运行良好,但有时我得到的数字高得离谱。
65535
而不是 511
。
只有当 lb
比 0x80
大时才会发生,但 hb
的大小无关紧要。
那么为什么
0x70 == '\x70'
但是0x80 != '\x80'
(在某些情况下)
在写题的时候发现
signed char
和char
如果是>= 0x80
的话会被区别对待。 (见下面的例子)
有人能解释为什么会这样吗?为什么会这样甚至在进行位操作时发生?
为什么不重要
hb
我认为这些例子解释得最好
#include <string>
using namespace std;
int main()
{
//different
uint8_t hb = 0x01;
uint8_t lb = 0xff;
uint16_t universe = (hb << 8) | lb;
cout<<universe << endl; //511
string line = string("\x01\xff");
universe = (line[0] << 8) | line[1];
cout<<universe << endl; //65535
//different
hb = 0x10;
lb = 0x80;
universe = (hb << 8) | lb;
cout<<universe << endl; //4224
line = string("\x10\x80");
universe = (line.at(0) << 8) | line.at(1);
cout<<universe << endl; //65408
universe = ('\x10' << 8) | '\x80';
cout<<universe << endl; //65408 too
//this is fine
hb = 0x83;
lb = 0x70;
universe = (hb << 8) | lb;
cout<<universe << endl; //33648
line = string("\x83\x70");
universe = (line[0] << 8) | line[1];
cout<<universe << endl; //33648
//so it is only happening if lower byte is > 0x80
if(0x70 == '\x70')
cout << "same 0x70" << endl; //same
unsigned char nn = '\x80';
if(0x80 == nn)
cout << "now its same 0x80 again " << endl; //same
uint8_t n = '\x80';
if(0x80 == n)
cout << "now its same 0x80 again " << endl; //same
if(0x80 == '\x80')
cout << "not same 0x80" << endl; //actually not the same ??
if(nn == '\x80')
cout << "not same 0x80" << endl; //actually not the same ??
char nnn = '\x80';
if(nnn == '\x80')
cout << "same 0x80" << endl; //same I THINK THIS IS THE DIFFERENCE
out << sizeof(nn) << sizeof(n) << sizeof(lb)<< sizeof(lb)<<endl; //1 1 1 1
//AND WHY IS THIS WORKING ? here is a value > 0x80 used but its working fine
hb = 0x90;
lb = 0x70;
universe = (hb << 8) | lb;
cout<<universe << endl; //36976
line = string("\x90\x70");
universe = (line[0] << 8) | line[1];
cout<<universe << endl; //36976
return 0;
}
我通过将字符分配给
uint8_t
来修复它在我的代码中。但我不明白为什么会这样。为什么 char
和 unsigned Char
在位操作上的处理方式不同?
string line = string("\x01\xff");
uint8_t hb = line[0];
uint8_t lb = line[1];
universe = (hb << 8) | lb;
cout<<universe << endl; //65535