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 to change the first four bits in single_char to represent values ​​between 1..10 (int)?

The question arose from the 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 a value of 4..5, the value of char is 0xA0.

+5
source share
4 answers

They have the assumption that you initialized * single_char to some value. Otherwise, the caf decision is published what you need.

(*single_char) = ((*single_char) & 0xF0) | val;

  • (*single_char) & 11110000 - Resets low 4 bits to 0
  • | val - sets the last 4 bits to a value (provided that val is <16)

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

4 , 4, ..

unsigned char v = (*single_char) & 0xF0;

:

(*single_char) = ((*single_char) & 0x0F) | (val << 4);

+7

4 *single_char 4 :

unsigned data_offset = 5; /* Or whatever */

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

.

+3

, , , , -

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

, -

+2

All Articles