idude
idude

Reputation: 4912

Not Operation on Unsigned Int in Java

So I now ~n gives me the not operation on the integer n, but is there any way I can read this as an unsigned int?

For example ~50, I get -51, when I actually want 13. Is there any way to do this in Java?

So for example, 50 in binary is 110010. When the digits are inverted, we should get 001101.

Upvotes: 0

Views: 585

Answers (2)

DAle
DAle

Reputation: 9117

If you want to keep the leading zero bits unchanged, you can set them to zero after the 'binary not' operation. All we need is to create the 11...1 mask with the number of 1's equal to the number of significant bits in n, then we can set to zero all other bits:

int invert(int n) {
    int mask = (Integer.highestOneBit(n) << 1) - 1;
    return (~n & mask);  
}

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

There are 32 bits, and all those leasing zeroes become ones.

int mask = Integer.highestOneBit(n) << 1:
return ~n & - - mask;

Upvotes: 0

Related Questions