我有一个赋值,我必须将4个unsigned char中的字节打包成unsigned int。
代码如下:
#include <stdio.h>
int main (){
//Given this
unsigned char a = 202;
unsigned char b = 254;
unsigned char c = 186;
unsigned char d = 190;
//Did this myself
unsigned int u = a;
u <<=8;
u |= b;
u <<=8;
u |= c
u <<=8;
U |= d;
}
我知道:
u <<=8;
将你的位向左移动8.但我对u |= b;
do这些线条感到困惑?
简单地说,我试图更好地理解我所编写的代码将4个unsigned char中的字节打包成unsigned int。我以粗野的方式提出了这个解决方案。我只是试图以不同的方式打包字节,这种方式有效。但我不确定为什么。
先感谢您。
a
是二进制的202
将是11001010
b
是二进制的254
将是11111110
c
是二进制的186
将是10111010
d
是二进制的190
将是10111110
unsigned int u = a;
u <<= 8; // now u would be 11001010 00000000
u |= b; // now u would be 11001010 11111110
u <<= 8; // now u would be 11001010 11111110 00000000
u |= c; // now u would be 11001010 11111110 10111010
u <<= 8; // now u would be 11001010 11111110 10111010 00000000
u |= d; // now u would be 11001010 11111110 10111010 10111110
// This is how a b c d
// are packed into one integer u.
u | = b表示u = u OR b因此,这是OR运算