Bit manipulation

suggest change

Bit manipulation means working on the individual bits of an integer: testing and setting flags, packing several small values into one Int or Long, or using tricks such as "is this a power of two?" that run in a few CPU instructions.

Kotlin has no &, |, ^, ~, <<, >> or >>> operators. It uses infix functions with names instead:

Java Kotlin Meaning
a & b a and b 1 where both bits are 1
a | b a or b 1 where either bit is 1
a ^ b a xor b 1 where the bits differ
~a a.inv() flip every bit
a << n a shl n shift left, fill with zeros
a >> n a shr n shift right, copy the sign bit
a >>> n a ushr n shift right, fill with zeros

The shifts are defined for Int, Long and the unsigned UInt and ULong. This article covers binary literals and formatting, two's complement, shifts, single-bit operations, the standard library bit functions, common tricks, packing bit fields, unsigned types, BitSet and bit masks used as sets. For bit operations on Byte and ByteArray (signed bytes, endianness, ByteBuffer) see Bytes and binary data.

The basic operations

fun Int.bin(width: Int = 8) = toString(2).padStart(width, '0')

fun main() {
    val a = 0b1100_1010
    val b = 0b0101_1100
    println("a       = ${a.bin()}")
    println("b       = ${b.bin()}")
    println("a and b = ${(a and b).bin()}")
    println("a or b  = ${(a or b).bin()}")
    println("a xor b = ${(a xor b).bin()}")
    println("a shl 2 = ${(a shl 2).bin(10)}")
    println("a shr 3 = ${(a shr 3).bin()}")
    println("a.inv() = ${a.inv()}")
    println("        = ${a.inv().toUInt().toString(2)}")
}

Output:

a       = 11001010
b       = 01011100
a and b = 01001000
a or b  = 11011110
a xor b = 10010110
a shl 2 = 1100101000
a shr 3 = 00011001
a.inv() = -203
        = 11111111111111111111111100110101

Printing and parsing binary

Int.toString(2) prints a signed number in base 2, so negative values get a minus sign rather than their bit pattern. To see the actual 32 bits, convert to UInt first or use the JDK's Integer.toBinaryString:

fun main() {
    val x = -8
    println(x.toString(2))
    println(x.toUInt().toString(2))
    println(x.toUInt().toString(2).padStart(32, '0').chunked(8).joinToString("_"))
    println(Integer.toBinaryString(x))
    println(x.toHexString())
    println(5.toByte().toString(2).padStart(8, '0'))
    println((-1).toByte().toUByte().toString(2))

    println("1011".toInt(2))
    println("-101".toInt(2))
    println("ffffffff".toUInt(16).toInt())
    println("11111111111111111111111111111000".toUInt(2).toInt())
    println("11111111111111111111111111111000".toIntOrNull(2))
}

Output:

-1000
11111111111111111111111111111000
11111111_11111111_11111111_11111000
11111111111111111111111111111000
fffffff8
00000101
11111111
11
-5
-1
-8
null

Parsing has the same issue in reverse. "ffffffff".toInt(16) throws NumberFormatException because 4294967295 doesn't fit in an Int. Parse it as UInt and convert with toInt(), which keeps the bits. toHexString() (stable since Kotlin 2.2) always prints the full width of the type, which is often what you want when looking at bits.

Two's complement

Kotlin's Byte, Short, Int and Long are signed two's complement numbers, like in Java. The highest bit is the sign bit, and -x equals x.inv() + 1:

fun main() {
    println(Int.MAX_VALUE.toHexString())
    println(Int.MIN_VALUE.toHexString())
    println(Int.MAX_VALUE + 1)
    println(-5 == 5.inv() + 1)
    println(-Int.MIN_VALUE)
    println(kotlin.math.abs(Int.MIN_VALUE))
    try {
        Math.addExact(Int.MAX_VALUE, 1)
    } catch (e: ArithmeticException) {
        println("addExact: ${e.message}")
    }
}

Output:

7fffffff
80000000
-2147483648
true
-2147483648
-2147483648
addExact: integer overflow

Arithmetic silently wraps around on overflow. Int.MIN_VALUE has no positive counterpart, so negating it or taking its abs returns Int.MIN_VALUE again. Use Math.addExact, multiplyExact and friends when overflow must be detected, or BigInteger when numbers can be arbitrarily large.

Shifts

fun main() {
    println(-16 shr 2)
    println(-16 ushr 2)
    println(-16 ushr 28)
    println(-7 shr 1)
    println(-7 / 2)

    // shift distance is taken modulo the bit width
    println(1 shl 31)
    println(1 shl 32)
    println(1 shl 33)
    println(1L shl 32)
    println(1 shl -1)
}

Output:

-4
1073741820
15
-4
-3
-2147483648
1
2
4294967296
-2147483648

Things to know:

Testing, setting and clearing bits

These four operations come up constantly. Extension functions make them read well:

fun Int.isBitSet(n: Int) = (this shr n) and 1 == 1
fun Int.setBit(n: Int) = this or (1 shl n)
fun Int.clearBit(n: Int) = this and (1 shl n).inv()
fun Int.toggleBit(n: Int) = this xor (1 shl n)
fun Int.withBit(n: Int, on: Boolean) = if (on) setBit(n) else clearBit(n)

fun main() {
    var v = 0b0000_0101
    println(v.isBitSet(0))
    println(v.isBitSet(1))
    v = v.setBit(3)
    println(v.toString(2))
    v = v.clearBit(0)
    println(v.toString(2))
    v = v.toggleBit(7)
    println(v.toString(2))
    v = v.withBit(7, false)
    println(v.toString(2))

    println(1L shl 40)
    println(1 shl 40)
}

Output:

true
false
1101
1100
10001100
1100
1099511627776
256

The last line is the shift-distance rule biting: 1 shl 40 is 1 shl 8. For bit positions 32 to 63 the mask must be a Long: 1L shl n.

Operator precedence

Because and, or, shl and the rest are ordinary infix functions, they all have the same precedence and are evaluated left to right. They bind looser than arithmetic (+, *) and tighter than comparisons (==, <):

fun main() {
    val hi = 0x12
    val lo = 0x34
    println((hi shl 8 or lo).toHexString())
    println((lo or hi shl 8).toHexString())
    println((lo or (hi shl 8)).toHexString())
    println(1 shl 2 + 1)
    val flags = 0b0110
    println(flags and 0b0010 != 0)
}

Output:

00001234
00003600
00001234
8
true

lo or hi shl 8 means (lo or hi) shl 8 in Kotlin, while the Java version lo | hi << 8 means lo | (hi << 8). When porting bit-twiddling code from Java or C, add parentheses around every shift. 1 shl 2 + 1 is 1 shl 3 because + binds tighter. flags and 0b0010 != 0 happens to work, but (flags and 0b0010) != 0 is clearer.

Standard library bit functions

The standard library has functions that compile to single CPU instructions on the JVM (via Integer and Long intrinsics):

fun main() {
    val n = 0b0010_1100_0000
    println(n.countOneBits())
    println(n.countLeadingZeroBits())
    println(n.countTrailingZeroBits())
    println(n.takeHighestOneBit().toString(2))
    println(n.takeLowestOneBit().toString(2))
    println(0.countTrailingZeroBits())
    println(0.takeHighestOneBit())

    println(0x12345678.rotateLeft(8).toHexString())
    println(0x12345678.rotateRight(4).toHexString())

    println(Integer.reverse(1).toHexString())
    println(Integer.reverseBytes(0x12345678).toHexString())
    println(java.lang.Long.bitCount(-1L))

    val b: Byte = 0b0101_0000
    println(b.countOneBits())
    println(b.countLeadingZeroBits())
    println(b.rotateLeft(2))
}

Output:

3
22
6
1000000000
1000000
32
0
34567812
81234567
80000000
78563412
64
2
1
65
Function Returns
countOneBits() number of 1 bits (population count)
countLeadingZeroBits() zeros above the highest 1 bit
countTrailingZeroBits() zeros below the lowest 1 bit
takeHighestOneBit() only the highest 1 bit kept
takeLowestOneBit() only the lowest 1 bit kept
rotateLeft(n) / rotateRight(n) bits shifted out on one side come back on the other

They exist for Int, Long, Byte, Short and the unsigned types, and work at the width of the type: b.countLeadingZeroBits() counts within 8 bits. On zero, the count functions return the bit width (32) and take...OneBit() returns 0. Reversing the bit order or byte order isn't in the common standard library, so use Integer.reverse, Integer.reverseBytes and their Long versions on the JVM.

Powers of two

fun Int.isPowerOfTwo() = this > 0 && (this and (this - 1)) == 0

fun log2(n: Int): Int {
    require(n > 0)
    return 31 - n.countLeadingZeroBits()
}

fun nextPowerOfTwo(n: Int): Int {
    require(n in 1..(1 shl 30))
    return if (n == 1) 1 else (n - 1).takeHighestOneBit() shl 1
}

fun bitLength(n: Long) = 64 - n.countLeadingZeroBits()

fun main() {
    println(listOf(0, 1, 2, 3, 64, 96, 1024).map { it.isPowerOfTwo() })
    println(listOf(1, 2, 3, 1000, 1024, 1025).map { log2(it) })
    println(listOf(1, 2, 3, 5, 64, 65, 1000).map { nextPowerOfTwo(it) })
    println(bitLength(255))
    println(bitLength(256))

    println(29 % 8)
    println(29 and 7)
    println(-29 % 8)
    println(-29 and 7)
    println(Math.floorMod(-29, 8))

    val align = 16
    println(listOf(0, 1, 15, 16, 17, 100).map { (it + align - 1) and (align - 1).inv() })
}

Output:

[false, true, true, false, true, false, true]
[0, 1, 1, 9, 10, 10]
[1, 2, 4, 8, 64, 128, 1024]
8
9
5
5
-5
3
3
[0, 16, 16, 16, 32, 112]

Don't use these as micro-optimizations for x * 8 or x / 4. The JIT already does that, and x / 4 and x shr 2 differ for negative numbers.

Lowest-bit tricks

Arithmetic on x - 1 and -x affects the lowest set bit in useful ways:

fun main() {
    val x = 0b1011_0100
    println((x and (x - 1)).toString(2))       // clear lowest set bit
    println((x and -x).toString(2))            // isolate lowest set bit
    println((x or (x - 1)).toString(2))        // fill bits below lowest set bit
    println((x or (x + 1)).toString(2))        // set lowest clear bit
    println((x.inv() and (x + 1)).toString(2)) // isolate lowest clear bit

    // iterate over set bits, lowest first
    var bits = x
    val positions = mutableListOf<Int>()
    while (bits != 0) {
        positions += bits.countTrailingZeroBits()
        bits = bits and (bits - 1)
    }
    println(positions)

    // mask of the low n bits
    fun lowMask(n: Int) = if (n >= 32) -1 else (1 shl n) - 1
    println(lowMask(5).toString(2))
    println(lowMask(32).toHexString())
    println((1 shl 32) - 1)
}

Output:

10110000
100
10110111
10110101
1
[2, 4, 5, 7]
11111
ffffffff
0

The loop that combines countTrailingZeroBits() with bits and (bits - 1) visits only the set bits, so it runs as many times as there are 1 bits rather than 32 times. The last line shows why lowMask needs a special case: (1 shl 32) - 1 is 0 because the shift wraps to 1 shl 0.

XOR

XOR has properties that make it handy: x xor x == 0, x xor 0 == x, and it's its own inverse.

fun main() {
    // every value appears twice except one
    val nums = listOf(4, 7, 2, 9, 7, 4, 2)
    println(nums.reduce { acc, v -> acc xor v })

    println(0x5A xor 0x5A)
    println(0x5A xor 0)

    fun sameSign(p: Int, q: Int) = (p xor q) >= 0
    println(sameSign(-3, -10))
    println(sameSign(-3, 10))

    // applying the same XOR key twice restores the data
    val key = 0x5A
    val data = "hi".encodeToByteArray()
    val enc = ByteArray(data.size) { (data[it].toInt() xor key).toByte() }
    val dec = ByteArray(enc.size) { (enc[it].toInt() xor key).toByte() }
    println(enc.toHexString())
    println(dec.decodeToString())

    // Gray code: neighbours differ in exactly one bit
    fun gray(n: Int) = n xor (n ushr 1)
    fun fromGray(g: Int): Int {
        var n = g
        var shift = g ushr 1
        while (shift != 0) { n = n xor shift; shift = shift ushr 1 }
        return n
    }
    println((0..7).map { gray(it).toString(2).padStart(3, '0') })
    println((0..7).map { fromGray(gray(it)) })
}

Output:

9
0
90
true
false
3233
hi
[000, 001, 011, 010, 110, 111, 101, 100]
[0, 1, 2, 3, 4, 5, 6, 7]

The XOR swap (a = a xor b; b = a xor b; a = a xor b) is a well-known trick, but in Kotlin a = b.also { b = a } is clearer and just as fast.

Packing fields into an Int

Packing several small values into one integer saves memory and is how many formats store data. An ARGB color stores four 8-bit channels in an Int:

// 0xAARRGGBB
fun argb(a: Int, r: Int, g: Int, b: Int): Int =
    ((a and 0xFF) shl 24) or ((r and 0xFF) shl 16) or ((g and 0xFF) shl 8) or (b and 0xFF)

val Int.alpha get() = this ushr 24
val Int.red get() = (this shr 16) and 0xFF
val Int.green get() = (this shr 8) and 0xFF
val Int.blue get() = this and 0xFF

fun Int.withRed(r: Int) = (this and 0x00FF0000.inv()) or ((r and 0xFF) shl 16)

fun main() {
    val c = argb(255, 0x33, 0x99, 0xCC)
    println(c.toHexString())
    println(c)
    println("a=${c.alpha} r=${c.red} g=${c.green} b=${c.blue}")
    println(c.withRed(0xEE).toHexString())

    // RGB565: 5 bits red, 6 bits green, 5 bits blue
    fun to565(r: Int, g: Int, b: Int) = ((r shr 3) shl 11) or ((g shr 2) shl 5) or (b shr 3)
    val p = to565(0x33, 0x99, 0xCC)
    println(p.toString(2).padStart(16, '0'))
    println(p.toShort().toHexString())
}

Output:

ff3399cc
-13395508
a=255 r=51 g=153 b=204
ffee99cc
0011010011011001
34d9

The recipe is always the same:

An opaque alpha makes the packed color negative as an Int, which is fine. That's why alpha uses ushr. This is exactly how Android's Color.argb() and Color.red() work.

Generic bit fields

For more complex layouts, write the shift-and-mask once and give the fields names. Here's a 64-bit Snowflake-style ID made of a 41-bit timestamp, 10-bit worker number and 12-bit sequence, wrapped in a value class so it costs no more than a Long:

fun Long.getField(offset: Int, width: Int): Long =
    (this ushr offset) and ((1L shl width) - 1)

fun Long.setField(offset: Int, width: Int, value: Long): Long {
    require(value ushr width == 0L) { "value $value does not fit in $width bits" }
    val mask = ((1L shl width) - 1) shl offset
    return (this and mask.inv()) or (value shl offset)
}

// sign-extend the low `width` bits
fun Long.signExtend(width: Int): Long {
    val shift = 64 - width
    return (this shl shift) shr shift
}

// Snowflake-style id: 41 bits timestamp | 10 bits worker | 12 bits sequence
@JvmInline
value class Id(val raw: Long) {
    val timestamp get() = raw.getField(22, 41)
    val worker get() = raw.getField(12, 10).toInt()
    val sequence get() = raw.getField(0, 12).toInt()

    override fun toString() = "Id(ts=$timestamp, worker=$worker, seq=$sequence)"

    companion object {
        fun of(timestamp: Long, worker: Int, sequence: Int) = Id(
            0L.setField(22, 41, timestamp)
                .setField(12, 10, worker.toLong())
                .setField(0, 12, sequence.toLong())
        )
    }
}

fun main() {
    val id = Id.of(timestamp = 1_234_567_890_123, worker = 17, sequence = 4095)
    println(id.raw)
    println(id)

    try {
        Id.of(1, worker = 1024, sequence = 0)
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }

    // a 12-bit signed sensor reading
    val raw = 0xFF6L
    println(raw.getField(0, 12))
    println(raw.signExtend(12))
}

Output:

5178153039814533119
Id(ts=1234567890123, worker=17, seq=4095)
value 1024 does not fit in 10 bits
4086
-10

signExtend handles signed fields narrower than the type, common in sensor data and instruction encodings. Shifting the field's top bit into the sign position and shifting back with shr copies it into all the higher bits, so 0xFF6 read as a 12-bit signed number becomes -10.

Unsigned types

UInt, ULong, UShort and UByte store the same bits as their signed counterparts, but comparisons, division, toString() and shr treat them as unsigned:

fun main() {
    val a: UInt = 0xF000_0000u
    println(a shr 28)
    println(a.toInt() shr 28)
    println(a > 0x7FFF_FFFFu)
    println(a.toInt() > 0x7FFF_FFFF)
    println(a.countOneBits())
    println(a.inv())
    println(a / 3u)

    val u = ULong.MAX_VALUE
    println(u)
    println(u.toString(16))

    val flags: UByte = 0b1000_0001u
    println(flags and 0x80u)
    println((flags.toUInt() shl 1).toUByte())

    // unsigned operations on signed Int, from the JDK
    println(Integer.toUnsignedString(-1))
    println(Integer.compareUnsigned(-1, 1) > 0)
    println(Integer.divideUnsigned(-2, 2))
}

Output:

15
-1
true
false
4
268435455
1342177280
18446744073709551615
ffffffffffffffff
128
2
4294967295
true
2147483647

On UInt there is no ushr: shr already shifts in zeros. Unsigned types are a good fit for hashes, checksums and protocol fields where the top bit isn't a sign. UByte and UShort have and, or, xor and inv but no shifts, so widen them to UInt first. Java APIs don't know about unsigned types; when you stay with Int, the Integer.*Unsigned methods give you unsigned comparison, division and printing.

BitSet

When you need more than 64 bits, java.util.BitSet is a growable array of bits backed by a LongArray. Here it is used for the Sieve of Eratosthenes:

import java.util.BitSet

fun primes(limit: Int): BitSet {
    val composite = BitSet(limit + 1)
    var i = 2
    while (i * i <= limit) {
        if (!composite[i]) {
            var j = i * i
            while (j <= limit) { composite.set(j); j += i }
        }
        i++
    }
    val result = BitSet(limit + 1)
    result.set(2, limit + 1)
    result.andNot(composite)
    return result
}

fun main() {
    val p = primes(50)
    println(p)
    println(p.cardinality())
    println(p[13])
    println(p.nextSetBit(20))
    println(p.previousSetBit(20))
    println(p.stream().filter { it > 40 }.toArray().toList())

    val a = BitSet().apply { set(1); set(3); set(5) }
    val b = BitSet().apply { set(3); set(4) }
    val union = (a.clone() as BitSet).apply { or(b) }
    val common = (a.clone() as BitSet).apply { and(b) }
    println("$union $common")

    println(a.toByteArray().toHexString())
    println(BitSet.valueOf(byteArrayOf(0b0000_0110, 1)))
}

Output:

{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}
15
true
23
19
[41, 43, 47]
{1, 3, 4, 5} {3}
2a
{1, 2, 8}

A million flags take about 125 KB in a BitSet versus roughly 1 MB in a BooleanArray and far more in a Set<Int>.

A 64-element set in a Long

When the universe has at most 64 elements, a single Long is the fastest set there is. A value class gives it a readable API:

@JvmInline
value class Bits64(val raw: Long = 0L) {
    operator fun get(i: Int): Boolean = (raw ushr i) and 1L == 1L
    operator fun plus(i: Int) = Bits64(raw or (1L shl i))
    operator fun minus(i: Int) = Bits64(raw and (1L shl i).inv())
    infix fun intersect(o: Bits64) = Bits64(raw and o.raw)
    infix fun union(o: Bits64) = Bits64(raw or o.raw)
    val size get() = raw.countOneBits()

    fun toList(): List<Int> {
        val out = ArrayList<Int>(size)
        var r = raw
        while (r != 0L) {
            out += r.countTrailingZeroBits()
            r = r and (r - 1)
        }
        return out
    }

    override fun toString() = toList().toString()
}

fun main() {
    val s = Bits64() + 1 + 5 + 63
    println(s)
    println(s[5])
    println(s[6])
    println((s - 5).size)
    println(s intersect (Bits64() + 2 + 63))
    println(s.raw.toULong().toString(16))
}

Output:

[1, 5, 63]
true
false
2
[63]
8000000000000022

Union, intersection and size are each a single instruction. Chess engines represent the board this way (one Long per piece type, one bit per square), and the same idea is behind java.util.EnumSet, which uses one long for enums with up to 64 constants. See Operator functions for more on get, plus and minus.

Enum flags and EnumSet

In application code, prefer EnumSet over raw Int flags: it's type-safe, prints nicely and is just as compact. Convert to a bit mask only at the boundary, when reading or writing a file format or a database column:

import java.util.EnumSet

enum class Perm { READ, WRITE, EXEC }

fun Set<Perm>.toMask(): Int = fold(0) { acc, p -> acc or (1 shl p.ordinal) }

fun permsOf(mask: Int): EnumSet<Perm> =
    Perm.entries.filterTo(EnumSet.noneOf(Perm::class.java)) { mask and (1 shl it.ordinal) != 0 }

fun main() {
    val perms = EnumSet.of(Perm.READ, Perm.EXEC)
    println(perms)
    println(Perm.WRITE in perms)
    val mask = perms.toMask()
    println(mask.toString(2))
    println(permsOf(0b011))
    println(permsOf(mask) == perms)
}

Output:

[READ, EXEC]
false
101
[READ, WRITE]
true

Using ordinal ties the stored format to the order of the enum constants. If the mask is persisted, give each constant an explicit bit property so reordering the enum doesn't silently change the meaning of stored data. See Enum for enums with properties.

Enumerating subsets

Each number from 0 until 2ⁿ corresponds to one subset of n items: bit i says whether item i is included. This gives a simple brute-force search over all combinations:

fun main() {
    val items = listOf("a", "b", "c")
    for (mask in 0 until (1 shl items.size)) {
        val subset = items.filterIndexed { i, _ -> mask and (1 shl i) != 0 }
        println("${mask.toString(2).padStart(3, '0')} $subset")
    }

    // all non-empty submasks of a mask
    val m = 0b1011
    var sub = m
    val subs = mutableListOf<String>()
    while (sub > 0) {
        subs += sub.toString(2)
        sub = (sub - 1) and m
    }
    println(subs)
}

Output:

000 []
001 [a]
010 [b]
011 [a, b]
100 [c]
101 [a, c]
110 [b, c]
111 [a, b, c]
[1011, 1010, 1001, 1000, 11, 10, 1]

(sub - 1) and m steps to the next smaller submask of m, visiting only combinations of bits that are set in m. This is a staple of dynamic programming over subsets. With an Int mask you can go up to 30 items, and 2³⁰ iterations is already a lot.

Common mistakes

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents