简体   繁体   中英

How do I cut off first bits in an unsigned long with bitwise?

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.

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

You can use also the >> << operators, the "12" in the code is the bit positions you you want to shift. The << operator shifts its left-hand operand left by the number of bits defined by its right-hand operand. The left-shift operation discards the high-order bits that are outside the range of the result type and sets the low-order empty bit positions to zero, then you can use the >> operand to restore the scale.

#include <stdio.h>

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

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

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM