详细地说,这里是:
作为直接答案;它们都将变量的字节存储在一个字节数组中,从左到右。tonet_short
对unsigned short
由 2 个字节组成的变量执行此操作;并对由 4 个字节组成的变量执行此tonet_long
操作。unsigned long
我将解释它tonet_long
,并且tonet_short
只是它的变体,您希望能够自己得出:
unsigned
变量,当它们的位被按位移位时,将它们的位向确定的一侧移动以确定数量的位,并且空出的位被设为0
零。IE:
unsigned char asd = 10; //which is 0000 1010 in basis 2
asd <<= 2; //shifts the bits of asd 2 times towards left
asd; //it is now 0010 1000 which is 40 in basis 10
请记住,这是针对unsigned
变量的,这些对于变量可能不正确signed
。
按位与&
运算符比较两侧的两个操作数的位,1
如果两者都为1
(true),则返回 (true),0
如果其中任何一个或两者都为(false),则返回0
(false);它对每一位都这样做。例子:
unsigned char asd = 10; //0000 1010
unsigned char qwe = 6; //0000 0110
asd & qwe; //0000 0010 <-- this is what it evaluates to, which is 2
现在我们知道了按位移位和按位与,让我们进入函数的第一行tonet_long
:
p[0] = (l >> 24) & 0xff;
在这里,由于l
is unsigned long
,(l >> 24)
将被计算为4 * 8 - 24 = 8
变量l
的第一位,即 的第一个字节l
。我可以像这样想象这个过程:
abcd efgh ijkl mnop qrst uvwx yz.. .... //letters and dots stand for
//unknown zeros and ones
//shift this 24 times towards right
0000 0000 0000 0000 0000 0000 abcd efgh
请注意,我们不会更改l
,这只是对 的评估l >> 24
,这是暂时的。
然后,0xff
它只是0000 0000 0000 0000 0000 0000 1111 1111
十六进制(以 16 为底),与 bitwise-shifted 进行按位与运算l
。它是这样的:
0000 0000 0000 0000 0000 0000 abcd efgh
&
0000 0000 0000 0000 0000 0000 1111 1111
=
0000 0000 0000 0000 0000 0000 abcd efgh
既然a & 1
会简单地严格依赖a
,那么就会a
;其余的也一样……这看起来像是一个多余的操作,而且确实如此。然而,这对其他人来说很重要。这是因为,例如,当您评估 时l >> 16
,它看起来像这样:
0000 0000 0000 0000 abcd efgh ijkl mnop
由于我们只想要ijkl mnop
部分,我们必须丢弃,这abcd efgh
将借助对应的位来完成。0000 0000
0xff
我希望这会有所帮助,其余的事情就像到目前为止一样,所以......是的。