-4

I have these bits 0010 1110 0101 0111.

Currently the value of bits from 7 to 11 (right to left) is 10011. I want to set it to 10110 for example. How do I do that?

Bhadresh
  • 15
  • 3

1 Answers1

2

This topic is common in the world of embedded systems. Usually, manufacturers of hardware devices use bit fields to represent information, such as statuses.

Inserting Into Your Number

This involves left shifting your number (such as birth year) into the appropriate position then ORing the value with your number:

unsigned int value;
//...
value |= (birth_year << 1);

Extracting or Getting the Number:

You will need to AND the number with a mask so that only the important bits are extracted. For example, retrieving gender:

unsigned int gender;
unsigned int value;
gender = value & 1;
// or 
gender = value & (~0);

You may need to right shift the bits to get the correct value, such as after extracting the birth year, right shift it by 1.

Bit Field Structure

You can let the Compiler figure all this by using bit fields in a structure, something like:

struct Compressed_Number
{
  unsigned int  gender : 1;
  unsigned int  birth_year : 11;
  //..
};

I personally prefer the Boolean Arithmetic version because you always know the bit positions.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154