Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 0x0000FFFFinstead. 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

like image 761
Tyler Kelly Avatar asked Feb 02 '16 16:02

Tyler Kelly


1 Answers

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
like image 77
dbush Avatar answered Nov 19 '22 17:11

dbush