如何更改 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,字符值类似于0xA0。
unsigned char *adata = (unsigned char*)malloc(500*sizeof(unsigned char));
unsigned char *single_char = adata+100;
How do I change first four bits in single_char to represent values between 1..10 (int)?
The question came from TCP header structure:
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.
Usually it has value of 4..5, the char value is like 0xA0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这些假设您已将 *single_char 初始化为某个值。否则,咖啡馆发布的解决方案可以满足您的需要。
<代码>(*single_char) = ((*single_char) & 0xF0) | val;
(*single_char) & 11110000
-- 将低 4 位重置为 0| 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);
These have the assumption that you've initialized *single_char to some value. Otherwise the solution caf posted does what you need.
(*single_char) = ((*single_char) & 0xF0) | val;
(*single_char) & 11110000
-- Resets the low 4 bits to 0| val
-- Sets the last 4 bits to value (assuming val is < 16)If you want to access the last 4 bits you can use
unsigned char v = (*single_char) & 0x0F;
If you want to access the higher 4 bits you can just shift the mask up 4 ie.
unsigned char v = (*single_char) & 0xF0;
and to set them:
(*single_char) = ((*single_char) & 0x0F) | (val << 4);
这会将 *single_char 的高 4 位设置为数据偏移量,并清除低 4 位:
This will set the high 4 bits of
*single_char
to the data offset, and clear the lower 4 bits:您可以使用按位运算符来访问各个位并根据您的要求进行修改。
You can use bitwise operators to access individual bits and modify according to your requirements.
我知道这是一篇旧文章,但我不希望其他人阅读有关按位运算符的长文章来获得与这些类似的函数 -
希望它对将来的人有所帮助
I know this is an old post but I don't want others to read long articles on bitwise operators to get a function similar to these -
Hope it helps someone in the future