I’m working with some binary numbers, trying to concatenate numbers. In this case, I would get what I wanted:
num = 0;
num = (num<<3)|4;
num = (num<<9)|7;
This would set num to 100000000111, or 0x0807 if I format to 4 hex digits.
However, if I try to concatenate a negative number:
num = 0;
num = (num<<3)|4;
num = (num<<9)|-7;
I get 0xFFF9, when I want to get 0x09F9. The right 9 bits appear to be correct, but it seems like some of the bits on the left are being flipped. I’m guessing that when I perform the logical or with the negative, the sign bit is being moved to the left most bit or something. Is there any way to prevent this?
Also, I am aware that in my example I could just set num to the number without the shifting, but in my actual program these are variables, and I just hard coded the numbers to demonstrate.
-7is probably a 32-bit negative number – that is,0xfffffff9. You need to mask it if you only want to use 9 bits: