如何在unsigned char中更改4位?

unsigned char *adata = (unsigned char*)malloc(500*sizeof(unsigned char)); unsigned char *single_char = adata+100; 

如何更改single_char中的前四位以表示介于1..10(int)之间的值?

问题来自TCP头结构:

 Data Offset: 4 bits The number of 32 bit words in the TCP Header. This indicates where the data begins. The TCP header (even one including options) is an integral number of 32 bits long. 

通常它的值为4..5,char值类似于0xA0。

这些假设您已将* single_char初始化为某个值。 否则,解决方案caf发布了你需要的东西。

(*single_char) = ((*single_char) & 0xF0) | val;

  1. (*single_char) & 11110000 – 将低4位重置为0
  2. | val | val – 将最后4位设置为value(假设val <16)

如果要访问最后4位,可以使用unsigned char v = (*single_char) & 0x0F;

如果你想访问更高的4位,你可以将掩码向上移动4即。

unsigned char v = (*single_char) & 0xF0;

并设置它们:

(*single_char) = ((*single_char) & 0x0F) | (val << 4);

这会将*single_char的高4位设置为数据偏移量,并清除低4位:

 unsigned data_offset = 5; /* Or whatever */ if (data_offset < 0x10) *single_char = data_offset << 4; else /* ERROR! */ 

您可以使用按位运算符访问各个位并根据您的要求进行修改。

我知道这是一篇旧post,但我不希望其他人阅读有关按位运算符的长篇文章,以获得类似于这些的函数 –

 //sets b as the first 4 bits of a(this is the one you asked for void set_h_c(unsigned char *a, unsigned char b) { (*a) = ((*a)&15) | (b<<4); } //sets b as the last 4 bits of a(extra) void set_l_c(unsigned char *a, unsigned char b) { (*a) = ((*a)&240) | b; } 

希望它能帮助将来的某个人