bit manipulation - Simple bitwise operation in Java -


i'm writing code in java using short typed variables. short variables 16 bits unfortunately java doesn't have unsigned primitive types i'm using 15 lower bits instead ignoring sign bit. please don't suggest changes part i'm quite far in implementation... here question:

i have variable need xor.

in c++ write

myunsignedshort = myunsignedshort ^ 0x2000;  0x2000 (hex) = 0010000000000000 (binary) 

however, in java, have deal sign bit i'm trying change mask doesn't affect xor...

mysignedshort = mysignedshort ^ 0xa000;  0xa000 (hex) = 1010000000000000 (binary) 

this isn't having desired effect , i'm not sure why. can see i'm going wrong?

regards.

edit: ok guys right, bit wasn't causing issue.

the issue comes when i'm shifting bits left.

i accidentally shift bits sign bit.

mysignedshort = mysignedshort << 1;

any ideas how avoid new prob if shifts msb nothing happens @ all? or should manual test? theres lot of shifting in code though prefer more terse solution.

regards.

those operations don't care signedness, mentioned in comments. can expand on that.

operations signed , unsigned versions same:

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

operations different:

  • division/remainder
  • right shift, there's >> , >>>
  • ordered comparison, can make a < b (a ^ 0x80000000) < (b ^ 0x80000000) change signed unsigned, or unsigned signed.
    can use (a & 0xffffffffl) < (b & 0xffffffffl) unsigned comparison, doesn't generalize longs.

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -