[英]packing unsigned char bytes into an unsigned int in c
I have an assignment in which I have to pack the bytes from 4 unsigned char into an unsigned int. 我有一个作业,其中我必须将4个无符号字符的字节打包成一个无符号int。
the code goes as following: 代码如下:
#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;
}
I know that: 我知道:
u <<=8;
Shifts the bits in u to the left 8. But I am confused as to what the lines like u |= b;
将u中的位向左移8。但是我对于像u |= b;
的行感到困惑u |= b;
do? 做?
Simply, I am trying to better understand what the code I came up works into packing the bytes from 4 unsigned char into an unsigned int. 简而言之,我试图更好地理解我提出的代码可以将4个无符号字符的字节打包为无符号int。 I came up with this solution in a brute type of way. 我以一种蛮横的方式提出了这个解决方案。 I was just trying to pack bytes in different ways, and this way worked. 我只是试图以不同的方式打包字节,这种方式有效。 But I am not really sure why. 但我不确定为什么。
Thank you in advance. 先感谢您。
a
which is 202
in binary would be 11001010
二进制为202
a
将是11001010
b
which is 254
in binary would be 11111110
b
二进制为254
为11111110
c
which is 186
in binary would be 10111010
二进制文件186
中的c
为10111010
d
which is 190
in binary would be 10111110
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运算
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.