优雅和最短的方法,只保存一半的字节

Elegant & shortest way to save only half of byte

本文关键字:保存 一半 字节 方法      更新时间:2023-10-16

有什么优雅而最短的方法可以做到这一点吗?

unsigned char someInteger(int someInt) {
// 00110110
unsigned char type[7];
type[7] = ((someInt >> 7) & 0x1);
type[6] = ((someInt >> 6) & 0x1);
type[5] = ((someInt >> 5) & 0x1);
type[4] = ((someInt >> 4) & 0x1);
type[3] = 0;
type[2] = 0;
type[1] = 0;
type[0] = 0;
return type; // 48
}

我只想有数字的第 4 位到 7 位。

多谢!

优雅和最短的方法,只保存一半的字节

可以使用按位 AND 将一半的位设置为零。例如:

unsigned char byte = 0b00110110;
unsigned char mask = (1 << CHAR_BIT / 2) - 1;
unsigned char half = byte & mask;

我只想有数字的第 4 位到 7 位。

同样,将 AND 与位掩码一起使用:

unsigned char byte = 0b00110110;
unsigned char mask = 0b01001000;
unsigned char b_4_7 = byte & mask;