How to get the last 16 binary digits of a negative number and combine them?

I work with some bitwise operators, and I want to extract the last 16 binary digits of a number and perform an operation with them. I basically want to see the negative int as 0xFFFFFFFF, and then extract the LSB FFFF and concatenate them with 0 so that I end up with zero, so that it looks like 0x0000FFFF . I only care about smaller negative numbers, so LSB should be all the necessary information.

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 is that I can convert my int a to short so that it looks like FFFF instead of FFFFFFFF . I will feel better. Unfortunately for me it just prints FFFFFFFF for variables

+5
source share
1 answer

What you have does not work, because the bitwise-OR ( | ) operator sets any bit that is set to any of the operands.

You want to use the bitwise-AND ( & ) operator to mask the bits you need. This clears any bit that is clear on any of the operands.

Change this:

 c = (0 << 16) | b; 

For this:

 c = b & 0xFFFF; 

And your output will be:

 a is ffffffff b is ffffffff c is ffff 
+5
source

Source: https://habr.com/ru/post/1242108/


All Articles