Developer Bitwise

Bitwise calculator

Values are in
First value
Second value
Operation
Result 8
32-bit operations
Every operation on these two
In decimal 8
In binary 1000
In hex 0x8
A AND B 8
A OR B 14
A XOR B 6
NOT A 4294967283
32-bit operations

AND masks — it keeps only the bits set in both, so ANDing with 0x0F keeps the low nibble and clears the rest. OR sets — it turns bits on without disturbing the others. XOR toggles, and applying it twice with the same value returns the original, which is why it turns up in simple ciphers and in swapping without a temporary variable.

Operations are 32-bit, which is what JavaScript bitwise operators use. Values above 2³²−1 will wrap.

Advertisement
320 × 100

Bitwise operations compare two numbers bit by bit. 12 AND 10 is 8, because only the 8-bit is set in both. OR gives 14, XOR gives 6. Operations here are 32-bit.

How to use bitwise operations

1 Choose the base your two values are written in.
2 Enter both. Every operation is computed, not only the one you pick.
3 Read the binary row to see which columns survived.
4 NOT uses the first value only, and inverts all 32 bits of it.

The binary row is the one to read while learning. Bitwise operations are obvious once you can see the columns lining up — 1100 AND 1010 gives 1000 because only the leftmost column has a 1 in both. Everything else follows from that column-by-column comparison. Note that NOT operates on all 32 bits, so NOT 0 is 4294967295 rather than 1.

Four idioms cover almost all real use. To test a flag, AND with it and check the result is not zero. To set one, OR with it. To clear one, AND with its complement. To toggle one, XOR with it. Masking is the same move with several bits at once: B4 AND 0F is 04, the low nibble kept and the high one thrown away, which is how a packed field is pulled out of a byte.

The bug that catches everyone is precedence rather than logic. In C, JavaScript and most of what copied them, == binds more tightly than &, so flags & MASK == 0 is read as flags & (MASK == 0) and quietly evaluates to nothing useful. Put the AND in brackets. And & is not &&: one compares every bit of two numbers, the other stops at the first falsy operand and hands back a value rather than a bit pattern.

Questions

Keeps only bits set in both values. It is how masks work: B4 AND 0F is 04.

Advertisement
300 × 250
Was this tool any good?
Internal signal only · I use it to find the tools worth rebuilding