简体   繁体   English

C语言中的按位运算符:此函数如何工作?

[英]Bitwise operators in C: how this function works?

I can't figure out how this functions works: 我不知道此功能如何工作:

void print3bytes(unsigned char s[],unsigned len)
{
    unsigned char *end;
    for(end=s+len-len%3;  s<end;  s=s+3 )
        printf("%x ",  s[0]|s[1]<<8  |  s[2]<<16); 
    putchar('\n'); 
}

how does this work for this example: 此示例如何工作:

int main(void)
{
    unsigned char s[] = "\x12\x34\x56\x78\x9A\xBC\xDE\xFF";
    print3bytes(s, 8);
    return 0;
}

Could someone please explain? 有人可以解释一下吗?

The expression combines: 该表达式结合了:

  • The first byte s[0] 第一个字节s[0]
  • The second byte s[1] shifted (`<<´) 8 bits to the left 第二个字节s[1]向左移('<<´)8位
  • The third byte s[2] shifted ( << ) 16 bits to the left 第三个字节s[2]向左移( << )16位

using bitwise-or ( | ). 使用按位或( | )。

So, when s contains 0x12, 0x34, 0x56 as its first bytes, it computes 因此,当s的首字节包含0x12、0x34、0x56时,它将计算

0x12 | (0x34 << 8) | (0x56 << 16)
  ^       ^             ^
  |       |             |
s[0]     s[1]         s[2]

which is 这是

0x12 | 0x3400 | 0x560000

or 0x563412 . 0x563412 Basically it's unpacking (decoding, de-serializing, de-marshaling, whatever) a 24-bit integer in little-endian format from the start of s . 基本上,它是从s的开头以little-endian格式解压缩(解码,反序列化,解编组等)。

s[0] | s[1]<<8  |  s[2]<<16

Let's say s[2] is 0xff (255), s[1] is 0xaa (170) and s[0] is 0x11 (17). 假设s [2]为0xff(255),s [1]为0xaa(170),而s [0]为0x11(17)。 If you shift s[2] 16 bits, you get: 如果将s [2]移位16位,则会得到:

0xff0000

If you shift s[1] by 8bits, you get: 如果将s [1]移位8位,则会得到:

0x00aa00

And if you or these together you get 如果您或这些人在一起,您将得到

0xffaa00

And or this with s[0]: 和或与s [0]:

0xffaa11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM