【问题标题】:How to change 4 bits in unsigned char?如何更改无符号字符中的 4 位?
【发布时间】:2011-01-21 06:12:01
【问题描述】:
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。

【问题讨论】:

    标签: c tcp unsigned bits bit-shift


    【解决方案1】:

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

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

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

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

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

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

    并设置它们:

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

    【讨论】:

    • 在TCP头的具体情况下,这个八位字节的低4位是保留的,必须为零。
    • 啊好吧,那你的解决方案更好:)
    • @GWW,最后,你的解决方案对我有用。但它偶尔会设置奇怪的值..(例如,single_char 变为十六进制 0x86 而不是 0x80)。
    • @mhambra:在尝试任何位操作之前,您确定该值已初始化为 0 吗?
    • @mhambra:是的,但是 0b00001111 保留了低位。因此,在您的示例中,0x86 = 0b10000110,这意味着在您执行此操作之前设置了一些低位。
    【解决方案2】:

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

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

    【讨论】:

    • 所以它会改变前4位并且不会影响低位?谢谢!
    • @mhambra: "first" 是一个符号问题 - 它会改变 most Significant 4 位,这就是你想要的 TCP 标头的那个字段。正如我所写,它将清除(零)低 4 位 - 这也是您想要的 TCP 标头,其中那些低 4 位被保留并且必须为零。
    【解决方案3】:

    您可以使用bitwise operators 访问各个位并根据您的要求进行修改。

    【讨论】:

      【解决方案4】:

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

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

      希望对以后的人有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-13
        相关资源
        最近更新 更多