How to change 4 bits in unsigned char?

梦想的初衷 提交于 2019-12-06 04:22:48

问题


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.


回答1:


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 -- Resets the low 4 bits to 0
  2. | 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);




回答2:


This will set the high 4 bits of *single_char to the data offset, and clear the lower 4 bits:

unsigned data_offset = 5; /* Or whatever */

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



回答3:


You can use bitwise operators to access individual bits and modify according to your requirements.




回答4:


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 -

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

Hope it helps someone in the future



来源:https://stackoverflow.com/questions/4755940/how-to-change-4-bits-in-unsigned-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!