将 unsigned char 转换为 int 和 short
我是新手,所以我首先要说的是,当我查看一些代码时,我意识到这个函数对我来说没有一点意义.
I am new to this, so I will begin by saying that while I was looking over some code I realized that this function doesn't make one bit of sense to me.
如您所见,此特定函数使用位运算符将 4 个无符号字符元素转换为整数.
As you can see that this specific function uses bitwise operators to convert 4 unsigned char elements into integer.
//将一个四字符数组转换为整数,使用little-endian形式
//Converts a four-character array to an integer, using little-endian form
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?为什么这个函数需要位运算符?
I already know how bitwise operators and how char uses 1 byte and int uses 4 bytes. Why would moving char bits 24 bits to the left and than just explicitly converting it to int convert it into an int? Why is bitwise operators necessary for this function?
这个功能超出了我的理解范围,请解释一下这段代码以及它是如何工作的,或者至少给我一个链接来彻底解释这一点.
This function goes beyond my comprehension, please explain this code and how it works or at least give me a link that throughly explains this.
我到处寻找解释,但找不到.
I have looked everywhere for the explanation but could not find it.
这可能有一个足够简单的解释.
This probably has a simple enough explanation.
推荐答案
为什么这个函数需要位运算符?
Why is bitwise operators necessary for this function?
位运算符用于将四个单字节数字组装"成四字节数字.
Bitwise operators are used to "assemble" the four-byte number from four single-byte numbers.
假设您有四个 8 位数字,如下所示:
Let's say you've got four 8-bit numbers, like this:
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
轮班给你这个:
aaaaaaaa000000000000000000000000
00000000bbbbbbbb0000000000000000
0000000000000000cccccccc00000000
000000000000000000000000dddddddd
按位运算符 OR
可以让您从这四个部分中生成一个数字,因为 OR
将任何位 x
与零相加会产生 <代码>x代码>.如果像上面所示对齐四字节数字,每个位置只有一个非零位,因此按位 OR
会产生所需的结果:
Bitwise operator OR
lets you make a single number from these four parts, because OR
-ing any bit x
with a zero produces x
. If you align four-byte numbers like shown above, there is only one non-zero bit in each position, so bitwise OR
s produce the desired result:
aaaaaaaabbbbbbbbccccccccdddddddd
相关文章