c/c++语言开发共享如何在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;

    如果要访问最后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; } 

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

      以上就是c/c++开发分享如何在unsigned char中更改4位?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/562322.html

      (0)
      上一篇 2021年2月4日
      下一篇 2021年2月4日

      精彩推荐