Home > Enterprise >  How to insert a new Bit at MSB and ignoring all other bits
How to insert a new Bit at MSB and ignoring all other bits

Time:12-18

I found this: add a new bit to the left of byte and discard right bit of byte but:

x = 0x80000000 | (x >> 1);

doesn't seam what I'm looking for.

union {
  unsigned char byte_variable;
  // a structure with 8 single bit bit-field objects, overlapping the union member "byte"
  struct {
                unsigned b0: 1;
                unsigned b1: 1;
                unsigned b2: 1;
                unsigned b3: 1;
                unsigned b4: 1;
                unsigned b5: 1;
                unsigned b6: 1;
                unsigned b7: 1;
  };
} byte_8;

apparently setting a bit like this:

byte_8.b7 = 1;

doesn't work if you use a Union.

How to add a new bit at the MSB and disregarding or without altering all other bits in the variable.

byte_8.byte_variable;

CodePudding user response:

The ordering of bitfields within a union is implementation defined, so what you tried isn't guaranteed to work.

If you want to set the highest order bit in an unsigned char, just OR the variable with a value that has only that bit set:

unsigned char x;
// set x
x = x | 0x80;

CodePudding user response:

If you want a more general approach to set the msb you can do it as:

int setMSB(int x, int b){
    return b ? x | (1 << sizeof(x)*8-1) : x & ~(1 << sizeof(x)*8-1);
}

where x is the number (you can modify the x data type as you wish) and b is the bit to put. Note that it could be safe to check if b is either 0 or 1 (or better use boolean).

If you set b=1 the variable becomes x | 100... in this way you set the msb keeping the other bits consistent (as other users have suggested already).

Otherwise if you set b=0 the variable becomes x & 011... the msb will be 0 while the others bit don't change their value

  • Related