[英]Understanding the bit shifting in C++
I have to debug a C++ code authored by someone else. 我必须调试由其他人编写的C ++代码。 I have very little experience in bit shifting and hence this question.
我对位移的经验很少,因此这个问题。 Here is the modified(values and unrelated code to the bit shifting) version of the same code:
以下是相同代码的修改(值移位的不相关代码)版本:
void get16Bits1(const char * data)
{
cout<<(((uint32_t)((const uint8_t *)(data))[1]) << 8)<<endl;
cout<<(uint32_t)((const uint8_t *)(data))[0]<<endl;
}
int main(){
const char * data = "francesmccurdey\0";
get16Bits1(data);
return 0;
}
prints out: 打印出来:
29184
102
The part I don't get is the get16Bits1()
function, casting to uint32_t
changes the output. 我没有得到的部分是
get16Bits1()
函数,转换为uint32_t
改变输出。 When I have this: 当我有这个:
void get16Bits1(const char * data)
{
cout<<((const uint8_t *)(data))[1]<<endl;
cout<<((const uint8_t *)(data))[0]<<endl;
}
output is:
r
f
I am compiling using gcc compiler on linux architecture: x86_64 and byte order being little endian. 我正在使用linux架构上的gcc编译器进行编译:x86_64和字节顺序是小端。
cout<<(((uint32_t)((const uint8_t *)(data))[1]) << 8)<<endl;
data[1]
is 'r'
which is 0x72 in ASCII. data[1]
是'r'
,在ASCII中是0x72。
0x72 << 8 = 0x7200 = 29184
For the next line in get16Bits1()
: cout<<(uint32_t)((const uint8_t *)(data))[0]<<endl
对于
get16Bits1()
的下一行: cout<<(uint32_t)((const uint8_t *)(data))[0]<<endl
This line simply prints the value data[0] as uint32_t
. 该行只是将值data [0]打印为
uint32_t
。 data[0]
is 'f'
which is 0x66 in ASCII (102 in decimal). data[0]
是'f'
,在ASCII中为0x66(十进制为102)。
Does it help to see the output in hexadecimal? 以十六进制查看输出是否有帮助?
7200
66
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.