我是新手,首先想说的是当我查看一些代码时,发现这个函数对我来说毫无意义。
正如您所看到的,该特定函数使用位运算符将4个无符号字符元素转换为整数。
// 使用小端形式将四个字符数组转换为整数
int toInt(const char* bytes) {
return (int)(((unsigned char)bytes[3] << 24) |
((unsigned char)bytes[2] << 16) |
((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
short toShort(const char* bytes) {
return (short)(((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
我已知道位运算符和char使用1字节和int使用4字节。将char位移24位,然后仅显式地将其转换为int,为什么会将其转换为int?为什么这个函数需要位运算符?
这个函数超出了我的理解范围,请解释一下这段代码是如何工作的,或者至少给我一个链接,详细解释这个函数。
我已经到处查找解释,但找不到。
这可能有一个简单明了的解释。