Davide Angelocola

Bit Packing Is Everywhere: Java Edition

28 November 2026

Sometimes, in discussions with other developers, we joke that there are two kinds of programmers: those who do bit packing and those who don’t. A LinkedIn post1 listing three classic examples made me want to write down why it keeps showing up.

One long, several fields

A 64-bit integer can carry several independent fields. Each field gets a fixed range of bits: you read it with a shift and a mask, and write it with a mask and an OR. That removes lookups, saves memory, keeps related data in one cache line, and lets one compare-and-swap update several fields at once.

Where it shows up

In a 64-bit word:

Format Layout Benefit
Snowflake ID1 1 unused bit, 41-bit millisecond timestamp, 10-bit machine ID, 12-bit sequence IDs sort by creation time, and each machine generates 4096 per millisecond with no coordination
XFS inode number1 allocation group, block within the group, inode within the block the number is the disk address, so there is no inode table to search
x86-64 virtual address1 four 9-bit page-table indices, then a 12-bit page offset each index picks one of 512 8-byte entries, so a table fills exactly one 4 KB page
IEEE 754 double 1 sign, 11 exponent, 52 fraction bits positive doubles sort the same as their bits read as a long

The same trick at other widths:

Format Width Layout Benefit
UTF-82 8 bits per byte lead byte starts with 0, 110, 1110, or 11110 to give the length; continuation bytes start with 10 a decoder can resync from any byte
UUIDv73 128 bits 48-bit Unix millisecond timestamp in the high bits, then version, variant, and 74 random bits Snowflake without machine IDs: sortable by time, no coordination
IPv4 with CIDR 32 bits a /24 network is the top 24 bits of the address a subnet check is (addr & mask) == network
Unix permissions 12 bits rwx for user, group, and other, 3 bits each, plus setuid, setgid, and sticky 0755 is just those bits written in octal

Why it works

Four properties explain most of the appeal.

private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int COUNT_MASK = (1 << COUNT_BITS) - 1;

private static int runStateOf(int c)    { return c & ~COUNT_MASK; }
private static int workerCountOf(int c) { return c & COUNT_MASK; }

The CAS can still fail and retry under contention, and you can never atomically update more than one word this way.

A small Java codec

Java has no bitfields, so the discipline has to come from the code. Keep the whole layout in one class, name every width, shift and mask, and fail fast when a field is out of range instead of letting it overwrite its neighbor.

Each shift is the position of a field’s lowest bit, and each mask is the field’s width in ones:

 63 | 62 ........... 22 | 21 ......... 12 | 11 ........... 0
  0 |  millis (41 bits) | machine (10)    | sequence (12)
                        ^                 ^
                  TIME_SHIFT = 22   MACHINE_SHIFT = 12
public final class SnowflakeId {
    private static final int SEQUENCE_BITS = 12;
    private static final int MACHINE_BITS = 10;
    private static final int TIME_BITS = 41;

    private static final int MACHINE_SHIFT = SEQUENCE_BITS;
    private static final int TIME_SHIFT = SEQUENCE_BITS + MACHINE_BITS;

    private static final long SEQUENCE_MASK = (1L << SEQUENCE_BITS) - 1;
    private static final long MACHINE_MASK = (1L << MACHINE_BITS) - 1;
    private static final long TIME_MASK = (1L << TIME_BITS) - 1;

    private SnowflakeId() {}

    public static long encode(long millis, long machine, long sequence) {
        requireFits("millis", millis, TIME_MASK);
        requireFits("machine", machine, MACHINE_MASK);
        requireFits("sequence", sequence, SEQUENCE_MASK);
        return millis << TIME_SHIFT | machine << MACHINE_SHIFT | sequence;
    }

    public static long millis(long id)    { return id >>> TIME_SHIFT; }
    public static long machine(long id)   { return (id >>> MACHINE_SHIFT) & MACHINE_MASK; }
    public static long sequence(long id)  { return id & SEQUENCE_MASK; }

    private static void requireFits(String name, long value, long mask) {
        if ((value & ~mask) != 0) {
            throw new IllegalArgumentException(name + " out of range: " + value);
        }
    }
}

With real numbers, encode(1000, 5, 7) shifts each field into place and ORs them together:

millis    1000 << 22  = 0xFA000000
machine      5 << 12  = 0x00005000
sequence     7        = 0x00000007
                   OR = 0xFA005007

Decoding runs the same steps backward: shift the field down to bit 0, then mask off everything above it. millis needs no mask, since nothing sits above it.

millis    0xFA005007 >>> 22            = 1000
machine   (0xFA005007 >>> 12) & 0x3FF  = 5
sequence  0xFA005007 & 0xFFF           = 7

The test that matters is the round trip at the boundaries of every field. Each field at its maximum, with the others at zero, catches a field overwriting its neighbor:

@ParameterizedTest
@CsvSource({
    "0,             0,    0",
    "2199023255551, 0,    0",
    "0,             1023, 0",
    "0,             0,    4095",
    "2199023255551, 1023, 4095",
})
void roundTripsBoundaryValues(long millis, long machine, long sequence) {
    long id = SnowflakeId.encode(millis, machine, sequence);
    assertEquals(millis, SnowflakeId.millis(id));
    assertEquals(machine, SnowflakeId.machine(id));
    assertEquals(sequence, SnowflakeId.sequence(id));
}

@Test
void rejectsOutOfRangeFields() {
    assertThrows(IllegalArgumentException.class, () -> SnowflakeId.encode(0, 1024, 0));
}

Give the bits a type with Valhalla

The codec above is a bag of static methods over raw longs. Nothing stops you from passing an inode number to SnowflakeId.machine(...), or from swapping machine and sequence in encode(millis, sequence, machine): the compiler sees longs either way. Wrapper classes would fix that (the domain-primitive argument from Your Compiler Is Already Part of Your Security Team), but today each one costs a header and a pointer, which is exactly what packing was meant to avoid.

Value classes6 remove that trade-off, for the ID and for each field. Each field becomes a nested value record that owns its range check, and the ID keeps the same constants:

public value class SnowflakeId implements Comparable<SnowflakeId> {
    private static final int SEQUENCE_BITS = 12;
    private static final int MACHINE_BITS = 10;
    private static final int TIME_BITS = 41;

    private static final int MACHINE_SHIFT = SEQUENCE_BITS;
    private static final int TIME_SHIFT = SEQUENCE_BITS + MACHINE_BITS;

    private static final long SEQUENCE_MASK = (1L << SEQUENCE_BITS) - 1;
    private static final long MACHINE_MASK = (1L << MACHINE_BITS) - 1;
    private static final long TIME_MASK = (1L << TIME_BITS) - 1;

    public value record EpochMillis(long value) {
        public EpochMillis { requireFits("millis", value, TIME_MASK); }
    }

    public value record MachineId(int value) {
        public MachineId { requireFits("machine", value, MACHINE_MASK); }
    }

    public value record Sequence(int value) {
        public Sequence { requireFits("sequence", value, SEQUENCE_MASK); }
    }

    private final long bits;

    public SnowflakeId(long bits) {
        requireFits("bits", bits, Long.MAX_VALUE); // the top bit stays zero
        this.bits = bits;
    }

    public SnowflakeId(EpochMillis millis, MachineId machine, Sequence sequence) {
        this(millis.value() << TIME_SHIFT
             | (long) machine.value() << MACHINE_SHIFT
             | sequence.value());
    }

    public long bits()          { return bits; }
    public EpochMillis millis() { return new EpochMillis(bits >>> TIME_SHIFT); }
    public MachineId machine()  { return new MachineId((int) (bits >>> MACHINE_SHIFT & MACHINE_MASK)); }
    public Sequence sequence()  { return new Sequence((int) (bits & SEQUENCE_MASK)); }

    @Override
    public int compareTo(SnowflakeId that) {
        return Long.compare(bits, that.bits);
    }

    private static void requireFits(String name, long value, long mask) {
        if ((value & ~mask) != 0) {
            throw new IllegalArgumentException(name + " out of range: " + value);
        }
    }
}

The layout stays the same; only the API changes. Swapping two arguments is now a compile error, and every MachineId in the program is in range because the only way to get one is through its constructor. The raw-bits constructor and bits() are the way in and out of storage and the wire: a long read from a database column becomes a SnowflakeId after one sign check, with no decoding. Without identity, the JVM can keep each of these values in a register on hot paths, so the accessors don’t have to allocate, and == compares the bits.

There’s one caveat. Heap flattening has to stay atomic, and 64 bits of payload plus a null flag don’t fit in one 64-bit word. A SnowflakeId[] as dense as a long[] needs null-restricted types, which are still being designed (see Rethink Domain Primitives with Valhalla).

When not to pack

Bit packing is worth knowing because the same few operations (shift, mask, and OR) explain how a kernel finds an inode, how a CPU finds a page, and how a distributed system generates IDs with no coordination.

Pack when the layout is stable and the value sits on a hot path or is stored millions of times. If the data is variable-sized or likely to evolve, a plain object or a proper schema is easier to evolve.

Packing gives you speed and compactness at the cost of flexibility:


  1. The LinkedIn post covers Snowflake IDs, XFS inode numbers, and virtual address translation. ↩ ↩2 ↩3 ↩4

  2. RFC 3629: UTF-8, a transformation format of ISO 10646. ↩

  3. RFC 9562, section 5.7: UUID Version 7. ↩

  4. JEP 519: Compact Object Headers, a product feature since JDK 25, enabled with -XX:+UseCompactObjectHeaders. ↩

  5. C11, section 6.7.2.1, paragraph 11: “The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined.” Even a uint64_t bit-field is a compiler extension: paragraph 5 only guarantees _Bool, signed int, and unsigned int, and leaves any other type implementation-defined. ↩

  6. JEP 401: Value Classes and Objects, in preview on the Valhalla early-access builds targeting JDK 27. ↩