在MSB和LSB上写文章

Writing on MSB and on LSB of an unsigned Char

本文关键字:文章 LSB MSB      更新时间:2023-10-16

我有一个无符号字符,我想在四个最重要的四个最重要的情况下编写0x06,我想在其4个最不重要的位置上编写0x04。因此,字符表示应该像0110 0010

有些人可以指导我如何在C?

中做到这一点
c = (0x06 << 4) | 0x04;

因为:

0x04    = 0000 0100
0x06    = 0000 0110
0x06<<4 = 0110 0000
or op:  = 0110 0100

使用位移动运算符转移到正确的位置,并与位

结合
unsigned char c = (0x6 << 4) | 0x4;

要扭转该过程并提取比特菲尔德,您可以使用bitwise 使用掩码,其中只包含您感兴趣的位:

unsigned char lo4 = c & 0xf;
unsigned char hi4 = c >> 4;

首先,确保每 unsigned char八位:

#include <limits.h>
#if CHAR_BIT != 8
    #error "This code does not support character sizes other than 8 bits."
#endif

现在,假设您已经定义了一个unsigned char

unsigned char x;

然后,如果要完全设置unsigned char在高四位中有6个,而在低四位中有4位,请使用:

x = 0x64;

如果您想查看a的高位,而低位到b,请使用:

// Shift a to high four bits and combine with b.
x = a << 4 | b;

如果要将高位设置为a并保持低位不变,请使用:

// Shift a to high four bits, extract low four bits of x, and combine.
x = a << 4 | x & 0xf;

如果要将低位设置为b并保持高位不变,请使用:

// Extract high four bits of x and combine with b.
x = x & 0xf0 | b;

上述ab仅包含四位数值。如果他们可能设置了其他位,请分别使用(a & 0xf)(b & 0xf)代替上面的ab