Greg Peckory
Greg Peckory

Reputation: 8068

Boolean Logical not operator on Integer Java

Is there a method that takes in 16-bit unsigned integer, and performs a boolean logical NOT operation on it.

Upvotes: 3

Views: 1983

Answers (1)

aioobe
aioobe

Reputation: 421180

The bitwise negation-operator is ~. Example:

int i = 6;
System.out.println(~i);  // Prints -7

If you want to treat the integer as an unsigned 16-bit integer (i.e. disregard from the most significant 16 bits) you should do

public static int u16neg(int i) {
    return ~i & 0xFFFF;
}

Example:

System.out.println(u16neg(0b00000000_00000000_00000000_00000110)); // 65529
System.out.println(       0b00000000_00000000_11111111_11111001);  // 65529

Upvotes: 3

Related Questions