Binary Number Systems and Bitwise Manipulation in Java

In binary, the most significant bit (MSB) serves as the sign indicator: 0 for positive, 1 for negative.

For positive integers, the true form, one's complement, and two's complement are identical.

For negative integers:

  • One's complement is derived by inverting all bits of the true form except the sign bit.
  • Two's complement is calculated by adding 1 to the one's complement.
  • Conversely, the one's compliment can be found by subtracting 1 from the two's complement.
  • Zero is represented as all zeros in both one's and two's complement forms.

Java uses signed integers for all numeric types. Arithmetic operations are performed internally using two's complement representation. When interpreting a result, it must be converted back to its true form.

Bitwise Operators

Java supports seven bitwise operators:

  • & (AND): Result is 1 only if both bit are 1.
  • | (OR): Result is 1 if at least one bit is 1.
  • ^ (XOR): Result is 1 if the bits are different.
  • ~ (NOT): Inverts all bits.
  • >> (Signed Right Shift): Shifts bits right, filling the left with the sign bit.
  • << (Left Shift): Shifts bits left, filling the right with 0.
  • >>> (Unsigned Right Shift): Shifts bits right, filling the left with 0.

Note: There is no <<< operator.

Code Examples

AND Operation

// Example: 5 & 3
int numA = 5;  // Binary: 0101
int numB = 3;  // Binary: 0011
int resultAnd = numA & numB; // Result: 1 (Binary: 0001)

NOT Operation on Negative

// Example: ~(-4)
// -4 in two's complement (8-bit for simplicity): 11111100
// After NOT operation: 00000011 (which is 3)
int negValue = -4;
int resultNotNeg = ~negValue; // Result: 3

NOT Operation on Positive

// Example: ~6
// 6 in two's complement: 00000110
// After NOT: 11111001 (two's complement of -7)
int posValue = 6;
int resultNotPos = ~posValue; // Result: -7

Shift Operations

Signed Right Shift (>>)

int valRight = 16; // Binary: 00010000
int shiftedRight = valRight >> 3; // Result: 2 (Binary: 00000010)

Left Shift (<<)

int valLeft = 8; // Binary: 00001000
int shiftedLeft = valLeft << 2; // Result: 32 (Binary: 00100000)

Unsigned Right Shift (>>>) Fills the leftmost bits with 0, regardless of the sign.

Tags: binary bitwise java complement shifts

Posted on Thu, 07 May 2026 23:06:47 +0000 by michaelpalmer7