kagali-san
kagali-san

Reputation: 3082

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.

Upvotes: 4

Views: 7557

Answers (4)

Thomas
Thomas

Reputation: 487

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

Upvotes: 1

GWW
GWW

Reputation: 44161

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

Upvotes: 6

caf
caf

Reputation: 239321

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! */

Upvotes: 5

Praveen S
Praveen S

Reputation: 10393

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

Upvotes: 2

Related Questions