如何更改4位无符号的字符? [英] How to change 4 bits in unsigned char?

查看:228
本文介绍了如何更改4位无符号的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何更改前四位的single_char到1..10(INT)之间重新present值?

How do I change first four bits in single_char to represent values between 1..10 (int)?

问题来自TCP报头结构:

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.

通常它有4..5价值的char值就像0XA0。

Usually it has value of 4..5, the char value is like 0xA0.

推荐答案

这些有你已经初始化* single_char某个值的假设。否则张贴的解决方案CAF做你所需要的。

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;


  1. (* single_char)及11110000 - 将低4位为0

  2. | VAL - 设置最后4位值(假设VAL为< 16)

  1. (*single_char) & 11110000 -- Resets the low 4 bits to 0
  2. | val -- Sets the last 4 bits to value (assuming val is < 16)

如果您要访问的最后4位则可以使用
unsigned char型V =(* single_char)及为0x0F;

If you want to access the last 4 bits you can use unsigned char v = (*single_char) & 0x0F;

如果您要访问的高4位你可以移动掩模了4即

If you want to access the higher 4 bits you can just shift the mask up 4 ie.

unsigned char型V =(* single_char)及0XF0;

和对其进行设置:

(* single_char)=((* single_char)及为0x0F)| (VAL&LT;&4;);

这篇关于如何更改4位无符号的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆