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。

4

4 回答 4

6

这些假设您已将 *single_char 初始化为某个值。否则,发布的解决方案 caf 可以满足您的需求。

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

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

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

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

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

并设置它们:

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

于 2011-01-21T06:21:54.933 回答
5

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

unsigned data_offset = 5; /* Or whatever */

if (data_offset < 0x10)
    *single_char = data_offset << 4;
else
    /* ERROR! */
于 2011-01-21T06:23:01.983 回答
2

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

于 2011-01-21T06:16:20.347 回答
1

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

//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;
}

希望它在未来对某人有所帮助

于 2017-10-08T13:48:59.587 回答