I'm working on with some bitwise operators and I want to extract the last 16 binary digits of a number and do an operation with them. I basically want to see a negative int like 0xFFFFFFFF and then extract the LSB FFFF
and concatenate them with 0
so that I end up with a zero so that it looks like 0x0000FFFF
instead. I only care about smaller negative numbers so the LSB should be all the info I need.
Here is my approach in C:
#include <stdio.h>
int main(){
int a = -1, c = 0;
short b = (short)a;
printf("a is %x\nb is %x",a,b);
c = (0 << 16) | b;
printf("\nc is %x\n", c);
return 0;
}
My thought process being that I can convert my int a
to a short so that it looks like FFFF
instead of FFFFFFFF
I will have a better time. Unfortunately for me, this just prints out ffffffff
for the variables
What you have doesn't work because the bitwise-OR operator (|
) sets any bit which is set in either operand.
You want to use the bitwise-AND operator (&
) to mask out the bits you don't want. This clears any bit which is clear in either operand.
Change this:
c = (0 << 16) | b;
To this:
c = b & 0xFFFF;
And your output will be:
a is ffffffff
b is ffffffff
c is ffff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With