简体   繁体   中英

Simple bitwise operation in Java

I'm writing code in Java using short typed variables. Short variables are normally 16 bits but unfortunately Java doesn't have unsigned primitive types so I'm using the 15 lower bits instead ignoring the sign bit. Please don't suggest changes to this part as I'm already quite far in this implementation... Here is my question:

I have a variable which I need to XOR.

In C++ I would just write

myunsignedshort = myunsignedshort ^ 0x2000;

0x2000 (hex) = 0010000000000000 (binary)

However, in Java, I have to deal with the sign bit also so I'm trying to change my mask so that it doesn't affect the xor...

mysignedshort = mysignedshort ^ 0xA000;

0xA000 (hex) = 1010000000000000 (binary)

This isn't having the desired effect and I'm not sure why. Anyone can see where I'm going wrong?

Regards.

EDIT: ok you guys are right, that bit wasn't causing the issue.

the issue comes when I'm shifting bits to the left.

I accidentally shift bits into the sign bit.

mysignedshort = mysignedshort << 1;

Any any ideas how to avoid this new prob so that if it shifts into the MSB then nothing happens at all? or should I just do a manual test? Theres a lot of this shifting in the code though so I would prefer a more terse solution.

Regards.

Those operations don't care about signedness, as mentioned in the comments. But I can expand on that.

Operations for which the signed and unsigned versions are the same:

  • addition/subtraction
  • and/or/xor
  • multiplication
  • left shift
  • equality testing

Operations for which they are different:

  • division/remainder
  • right shift, there's >> and >>>
  • ordered comparison, you can make a < b as (a ^ 0x80000000) < (b ^ 0x80000000) to change from signed to unsigned, or unsigned to signed.
    You can also use (a & 0xffffffffL) < (b & 0xffffffffL) to get an unsigned comparison, but that doesn't generalize to longs.

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