Home > Mobile >  Using bitwise operators to change all bits of the most significant byte to 1
Using bitwise operators to change all bits of the most significant byte to 1

Time:08-21

Let's suppose I have an unsigned int x = 0x87654321. How can I use bitwise operators to change the most significant byte (the leftmost 8 bits) of this number to 1?

So, instead of 0x87654321, I would have 0xFF654321?

CodePudding user response:

The value UINT_MAX has all bits set. As an unsigned in C may be 32 bits, 16 bits or other sizes, best to drive code without assuming the width.

The value UINT_MAX has all value bits set.

A "byte" in C is CHAR_BIT wide - usually 8.

UINT_MAX ^ (UINT_MAX >> CHAR_BIT) is the desired mask.

#include <limits.h>
#include <stdio.h>

#define UPPER_BYTE_MASK (UINT_MAX ^ (UINT_MAX >> CHAR_BIT))
// or 
#define UPPER_BYTE_MASK (~(UINT_MAX >> CHAR_BIT))

int main() {
  unsigned value = 0x87654321;
  printf("%X\n", value | UPPER_BYTE_MASK);
}

CodePudding user response:

#define MSB1(x)  ((x) | (0xffULL << ((sizeof(x) - 1) * 8)))


int main(void)
{
    char x;
    short y;
    int z;
    long q;
    long long l;

    printf("0x%llx\n", (unsigned long long)MSB1(x));
    printf("0x%llx\n", (unsigned long long)MSB1(y));
    printf("0x%llx\n", (unsigned long long)MSB1(z));
    printf("0x%llx\n", (unsigned long long)MSB1(q));
    printf("0x%llx\n", (unsigned long long)MSB1(l));

    l = MSB1(l);

}

CodePudding user response:

If you know the size of the integer, you can simply use something like

x |= 0xFF000000;

If not, you'll need to calculate the mask. One way:

x |= UINT_MAX - ( UINT_MAX >> 8 );
  • Related