bitlvl
EN

Bitmask calculator

Type bit positions to build a mask, or paste a mask to see which bits it contains. Click bits in the register to adjust. Name the bits and the tool writes the constants for you.

Width

Named flags

Give the set bits names and get constants in the language you use. Leave a name empty to skip that bit.

  

What a bitmask is

A bitmask is a number used for its bit pattern rather than its value. Each bit position stands for one on/off option, so a single integer can hold 8, 32 or 64 flags at once. Permissions (rwx), file-open modes, CPU feature bits, network masks and option sets in almost every C API are bitmasks.

Bit n has the value 2ⁿ, so a mask with bits 0, 2 and 7 set is 1 + 4 + 128 = 133 = 0x85 = 1000 0101. To make the constant in code you shift a 1 into position: 1 << 7.

Using a mask

Want to…Do this
Check if a flag is set(value & FLAG) != 0
Check if all of several flags are set(value & MASK) == MASK
Set a flagvalue |= FLAG
Clear a flagvalue &= ~FLAG
Toggle a flagvalue ^= FLAG
Extract a field of bits 4–7(value >> 4) & 0xF
Build a mask for bits lo..hi((1 << (hi - lo + 1)) - 1) << lo

Reading a mask you were given

Convert the value to binary and number the bits from the right starting at 0. Every 1 is a set flag. The tool above does this for any value you paste, and shows the positions as a compact list such as 0-2, 5, 7.

Examples

Unix permissions 0755
bits 0, 2, 3, 5, 6, 7, 8 → 1 1110 1101
Subnet mask /20
top 20 bits of 32 set → 0xFFFFF000
Low nibble
bits 0-3 → 0x0F

Questions

Why do bit positions start at 0?

Because bit n has the value 2ⁿ, and 2⁰ = 1 is the rightmost bit. Numbering from 0 makes the arithmetic line up: shifting by n puts a 1 at bit n.

What is the difference between a bitmask and a bit field?

A bitmask is the number you AND or OR with. A bit field is a group of adjacent bits inside a larger value that together store a small number (for example bits 4–7 holding a value 0–15). You use a mask and a shift to read or write a bit field.

How many flags fit in an integer?

One per bit: 8 in a byte, 32 in a 32-bit int, 64 in a 64-bit int. If you need more, use an array of integers or a dedicated bitset type.

Why use 1 << n instead of writing the number?

It documents which bit you mean and cannot be mistyped as a different power of two. Compilers fold it to a constant, so there is no runtime cost.

Does the tool handle 64-bit masks correctly?

Yes. It uses arbitrary-precision integers, so all 64 bits are exact, including bit 63.