Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change 4 bits in unsigned char?

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.

like image 529
kagali-san Avatar asked Dec 09 '22 11:12

kagali-san


1 Answers

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);

like image 153
GWW Avatar answered Dec 26 '22 18:12

GWW