Boneyard Tools

Bitwise operations explained with byte examples

How AND, OR, XOR, NOT and shifts work bit by bit, why width and twos complement matter, and how to use masks to set, clear and test bits.

Bits, width and masks

A bitwise operation looks at two numbers one bit position at a time rather than treating them as whole quantities. Before that can happen, both values are lined up to a fixed width, here 8, 16, 32 or 64 bits, and padded with leading zeros. The width matters because it decides how many bit positions exist and where the sign bit sits. A mask is simply a value chosen so that its 1 bits mark the positions you care about, which is the foundation of most bit tricks.

AND, OR and XOR in practice

AND returns a 1 only where both inputs have a 1, so it clears every bit outside a mask: 0xF0 AND 0x0F is 0x00 because their set bits never overlap. OR returns a 1 where either input has a 1, which is how you set bits. XOR returns a 1 only where the inputs differ, which flips selected bits and is reversible: applying the same XOR twice returns the original value. These three cover most flag manipulation you will meet.

NOT, NAND, NOR and XNOR

NOT inverts every bit within the width, so at 8 bits NOT 0x0F becomes 0xF0, an unsigned 240 that reads as signed -16 under twos complement. NAND, NOR and XNOR are just AND, OR and XOR followed by that same inversion. Seeing both the unsigned and signed decimal for a result, as the calculator shows, makes it obvious why a small negative number and a large unsigned number can share one bit pattern.

Shifting bits left and right

A left shift moves every bit toward the high end and drops in zeros on the right, which multiplies by two per position: 1 shifted left by 4 gives 0x10, decimal 16. A logical right shift does the reverse and divides by two, discarding the low bits. Because this tool treats operands as unsigned within the width, right shifts always bring in zeros, and shifting by the full width or more clears the value to zero.

Frequently asked questions

Why does AND with a mask clear bits?

AND keeps a bit only when both operands have a 1 there. A mask with 0s in the positions you want gone forces those results to 0 while leaving the masked-in positions untouched, so it is the standard way to isolate or clear a field.

Why does the same value show two different decimals?

The Decimal row reads the bits as an unsigned number and the Signed row reads them as twos complement. An 8-bit 11110000 is 240 unsigned but -16 signed; both are correct interpretations of one pattern, and which you want depends on the data type.