Master Java Bitwise Operations: From Binary Basics to Advanced Tricks
This tutorial explains Java's signed two's complement representation, demonstrates how to output binary strings, covers all bitwise operators (AND, OR, XOR, NOT, shifts), clarifies original/one's/complement forms, shows overflow handling, unsigned tricks with masking, and teaches packing multiple boolean flags into a single byte for efficient storage.
Introduction
After studying this chapter you will master the basic concepts and syntax of bitwise operations in Java and learn some handy tricks.
Binary representation
Java uses signed two's complement representation. For example byte a = 33; prints 00100001, while byte b = -3; prints 11111101. The article shows how to output binary strings using Integer.toBinaryString and padding with %32s or %8s, adding &0xFF for unsigned bytes.
Bitwise operators
AND a & b: result bit is 1 only when both bits are 1.
OR a | b: result bit is 1 when at least one bit is 1.
XOR a ^ b: result bit is 1 when bits differ.
NOT ~a: flips all bits.
Left shift a << n and right shift a >> n (signed) / a >>> n (unsigned) are illustrated with diagrams.
Number systems and prefixes
Decimal numbers are written directly, binary with 0b, octal with leading 0, and hexadecimal with 0x. Suffixes such as L, F, D indicate the literal type.
Original code, one's complement, two's complement
The article explains how positive numbers have identical original, one's‑complement and two‑complement forms, while negative numbers are obtained by inverting bits and adding one. It shows conversion steps with examples like 0b10101000 → -88.
Overflow and storage range
For an n -bit signed type the range is -2^(n‑1) … 2^(n‑1)-1. Examples for byte, short, int are given, and casting between types is demonstrated, e.g. casting int 200 to byte yields -56.
Unsigned tricks with &0xFF
Masking with 0xFF clears the sign‑extension when a byte is promoted to int, allowing the original unsigned value (e.g., 200) to be recovered.
Storing multiple flags in one byte
Four independent boolean flags can be packed into a single byte using bit masks 0b00000001, 0b00000010, 0b00000100, 0b00001000. The article provides methods to set, clear and test a flag with |, &~ and (x & flag) != 0.
Practical use cases
These techniques are common in Android graphics, NIO selectors, network protocols and any situation where memory efficiency matters.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
