Home > Software design >  How do I cut off first bits in an unsigned long with bitwise?
How do I cut off first bits in an unsigned long with bitwise?

Time:10-08

I have m = 0x401e000000000000 and I want to get f = 0xe000000000000. Using bitwise operators, how would I do that in C? I used f = (m & 0xFFFFFFFFFFFFF);

but I just get 0.

CodePudding user response:

When run in IDEOne, it works

#include <stdio.h>

int main(void) {
  unsigned long m = 0x401e000000000000;
  unsigned long f = m & (0xFFFFFFFFFFFFF); // Expect value = 0xe000000000000.
  
  printf("Result f = 0x%0lX\n", f);
  
    return 0;
}

Output

Success #stdin #stdout 0s 5416KB
Result f = 0xE000000000000

CodePudding user response:

You can use also the >> << operators, the "12" in the code is the bit positions you you want to shift.

#include <stdio.h>

int main()
{
    unsigned long m = 0x401e000000000000;
    m = (m<<12);

    printf("Result f = 0x%0lX\n", m);

    return 0;
}
  • Related