任何人都可以详细解释这完成了什么?我试图学习c并且很难绕过它.
void tonet_short(uint8_t *p, unsigned short s) {
p[0] = (s >> 8) & 0xff;
p[1] = s & 0xff;
}
void tonet_long(uint8_t *p, unsigned long l)
{
p[0] = (l >> 24) & 0xff;
p[1] = (l >> 16) & 0xff;
p[2] = (l >> 8) & 0xff;
p[3] = l & 0xff;
}
Run Code Online (Sandbox Code Playgroud)
详细地说,这里是:
作为直接回答; 它们都从左到右将变量的字节存储在一个字节数组中.tonet_short为unsigned short变量做了那个,它由2个字节组成; 并且tonet_long会为unsigned long变量,其由4个字节.
我会解释它tonet_long,并且tonet_short只是它的变化,你希望能够自己得出它:
unsigned变量,当它们的位被逐位移位时,使它们的位向确定的一侧移位以确定比特量,并使空出的比特0为零.即:
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
Run Code Online (Sandbox Code Playgroud)
请记住,这是unsigned变量,这些变量可能不正确signed.
bitwise-and &运算符比较两边两个操作数的位,1如果两者都是1(true)则返回(true),0如果其中任何一个或两者都是0(false)则返回(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
Run Code Online (Sandbox Code Playgroud)
现在我们知道了按位移位和按位 - 并且,让我们到达函数的第一行tonet_long:
p[0] = (l >> 24) & 0xff;
Run Code Online (Sandbox Code Playgroud)
这里,因为l是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
Run Code Online (Sandbox Code Playgroud)
请注意,我们不会更改l,这只是评估l >> 24,这是暂时的.
然后,0xff它只是0000 0000 0000 0000 0000 0000 1111 1111十六进制(基数16),按位移位获得按位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
Run Code Online (Sandbox Code Playgroud)
由于a & 1将严格依赖a,所以它将是a; 其余的一样......看起来这是一个多余的操作,而且确实如此.然而,对其他人来说,这将是重要的.这是因为,例如,当您评估时l >> 16,它看起来像这样:
0000 0000 0000 0000 abcd efgh ijkl mnop
Run Code Online (Sandbox Code Playgroud)
因为我们只想要ijkl mnop一部分,我们不得不放弃abcd efgh,而将与的帮助下完成0000 0000的是0xff在其相应的位.
我希望这会有所帮助,剩下的就像它到目前为止一样,所以......是的.