Bytes and binary data

suggest change

Network protocols, file formats, hashes, encryption keys and compressed data all come down to sequences of bytes. In Kotlin they are represented by ByteArray, which compiles to Java's byte[] on the JVM.

The two things that trip people up most:

This article covers creating and copying byte arrays, signed vs unsigned bytes, hex and Base64, bitwise operations, reading and writing multi-byte integers, ByteBuffer, DataOutputStream, and checksums. For converting text to bytes and back see Unicode and encodings. For numeric conversions in general see Type conversion.

Creating a ByteArray

fun main() {
    val a = byteArrayOf(1, 2, 3)
    val zeros = ByteArray(4)
    val squares = ByteArray(5) { i -> (i * i).toByte() }
    val header = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47)

    println(a.contentToString())
    println(zeros.contentToString())
    println(squares.contentToString())
    println(header.contentToString())
    println(header.size)
}

Output:

[1, 2, 3]
[0, 0, 0, 0]
[0, 1, 4, 9, 16]
[-119, 80, 78, 71]
4

Signed bytes

A Byte is an 8-bit two's complement number. Bit pattern 1100 1000 (0xC8) means -56, not 200. Converting to Int with toInt() keeps the sign. To get the unsigned value, mask with 0xFF or convert to UByte:

fun main() {
    val b: Byte = 0xC8.toByte()
    println(b)                     // signed view
    println(b.toInt())             // sign-extended
    println(b.toInt() and 0xFF)    // unsigned value as Int
    println(b.toUByte())           // unsigned view
    println(b.toUByte().toInt())

    val x: Byte = 0x7F
    val y: Byte = 0x80.toByte()
    println(x > y)                                  // compares signed values
    println((x.toInt() and 0xFF) > (y.toInt() and 0xFF))
}

Output:

-56
-56
200
200
200
true
false

b.toInt() and 0xFF is the idiom you'll see in almost all JVM byte-handling code. Use it whenever a byte is used as a number: indexing a lookup table, comparing, summing or shifting.

Unsigned arrays

Kotlin has UByte and UByteArray. UByte itself is stable, but most UByteArray functions still need an opt-in:

@OptIn(ExperimentalUnsignedTypes::class)
fun main() {
    val bytes = ubyteArrayOf(0x89u, 0x50u, 0xFFu)
    println(bytes.contentToString())
    println(bytes.sum())
    val raw: ByteArray = bytes.asByteArray()   // no copy, same memory
    println(raw.contentToString())
    println(raw.asUByteArray()[2])

    val sum = byteArrayOf(-1, -1, 10).sumOf { it.toUByte().toInt() }
    println(sum)
}

Output:

[137, 80, 255]
472
[-119, 80, -1]
255
520

asByteArray() and asUByteArray() are views over the same memory, so they cost nothing. Most libraries (Java APIs, java.io, java.security) take and return ByteArray, so in practice you keep data in a ByteArray and convert single bytes with toUByte() or and 0xFF where needed.

Comparing byte arrays

fun main() {
    val a = byteArrayOf(1, 2, 3)
    val b = byteArrayOf(1, 2, 3)
    println(a == b)
    println(a.contentEquals(b))
    println(a.hashCode() == b.hashCode())
    println(a.contentHashCode() == b.contentHashCode())
    println(setOf(a, b).size)
}

Output:

false
true
false
true
2

The compiler warns about a == b on arrays. Use contentEquals and contentHashCode. Because of that, a ByteArray makes a poor key in a HashMap or element in a HashSet. Convert it to a String (hex or Base64) or wrap it in a class with proper equals.

The same goes for data classes. The generated equals compares array properties by reference, so override it:

data class Packet(val id: Int, val payload: ByteArray) {
    override fun equals(other: Any?): Boolean =
        other is Packet && id == other.id && payload.contentEquals(other.payload)
    override fun hashCode(): Int = 31 * id + payload.contentHashCode()
}

fun main() {
    val p1 = Packet(1, byteArrayOf(1, 2))
    val p2 = Packet(1, byteArrayOf(1, 2))
    println(p1 == p2)
    println(p1)
}

Output:

true
Packet(id=1, payload=[1, 2])

When comparing secrets such as MAC tags or password hashes, use java.security.MessageDigest.isEqual(a, b). It runs in constant time, while contentEquals returns early at the first difference, which leaks timing information.

Copying, slicing and concatenating

fun main() {
    val src = byteArrayOf(10, 20, 30, 40, 50)

    println(src.copyOf(3).contentToString())
    println(src.copyOf(7).contentToString())
    println(src.copyOfRange(1, 4).contentToString())
    println(src.sliceArray(2..3).contentToString())

    val dst = ByteArray(8)
    src.copyInto(dst, destinationOffset = 2, startIndex = 0, endIndex = 3)
    println(dst.contentToString())

    println((src + byteArrayOf(60, 70)).contentToString())
    dst.fill(-1, fromIndex = 5)
    println(dst.contentToString())
    println(src.reversedArray().contentToString())
}

Output:

[10, 20, 30]
[10, 20, 30, 40, 50, 0, 0]
[20, 30, 40]
[30, 40]
[0, 0, 10, 20, 30, 0, 0, 0]
[10, 20, 30, 40, 50, 60, 70]
[0, 0, 10, 20, 30, -1, -1, -1]
[50, 40, 30, 20, 10]

Avoid generic collection functions such as map, filter or toList() on large byte arrays. They return a List<Byte> that stores a reference to a boxed Byte per element, taking 4 to 8 times more memory and running slower. Use the array-returning variants such as sliceArray, copyOfRange or ByteArray(n) { ... }.

Hex

Since Kotlin 2.2 the standard library has stable hex support: toHexString(), hexToByteArray() and the HexFormat builder. Before that you'd write joinToString("") { "%02x".format(it) }.

fun main() {
    val data = "Kotlin".encodeToByteArray()
    println(data.toHexString())
    println(data.toHexString(HexFormat.UpperCase))

    val back = "4b6f746c696e".hexToByteArray()
    println(back.decodeToString())

    println(255.toHexString())
    println(255.toByte().toHexString())
    println(0xCAFEL.toHexString())
    println("ff".hexToInt())
    println("cafe".hexToUShort())
}

Output:

4b6f746c696e
4B6F746C696E
Kotlin
000000ff
ff
000000000000cafe
255
51966

toHexString() on numbers always prints the full width of the type: 8 digits for Int, 16 for Long. A Byte gets 2 digits, and the sign doesn't matter: (-1).toByte().toHexString() is ff. hexToByteArray() throws IllegalArgumentException for odd-length input or non-hex characters.

HexFormat controls separators, line breaks, case, prefixes and leading zeros:

fun main() {
    val format = HexFormat {
        upperCase = true
        bytes {
            bytesPerLine = 8
            bytesPerGroup = 4
            byteSeparator = " "
            groupSeparator = "  "
        }
    }
    val data = ByteArray(20) { it.toByte() }
    println(data.toHexString(format))

    val mac = byteArrayOf(0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E)
    println(mac.toHexString(HexFormat { upperCase = true; bytes.byteSeparator = ":" }))

    val numFmt = HexFormat { number { prefix = "0x"; removeLeadingZeros = true } }
    println(4096.toHexString(numFmt))
    println("0x1000".hexToInt(numFmt))
}

Output:

00 01 02 03  04 05 06 07
08 09 0A 0B  0C 0D 0E 0F
10 11 12 13
00:1A:2B:3C:4D:5E
0x1000
4096

Parsing with the same format accepts the separators: with val macFormat = HexFormat { upperCase = true; bytes.byteSeparator = ":" }, "00:1A:2B".hexToByteArray(macFormat) returns [0, 26, 43].

A hex dump

A classic xxd-style dump is useful when debugging a protocol or file format:

fun hexdump(data: ByteArray) {
    for (offset in data.indices step 16) {
        val chunk = data.copyOfRange(offset, minOf(offset + 16, data.size))
        val hex = chunk.joinToString(" ") { it.toHexString() }
        val ascii = chunk.joinToString("") { b ->
            val c = b.toInt() and 0xFF
            if (c in 0x20..0x7E) c.toChar().toString() else "."
        }
        println("%08x  %-47s  |%s|".format(offset, hex, ascii))
    }
}

fun main() {
    val data = "Hello, bytes!\n".encodeToByteArray() + byteArrayOf(0, 1, -1) +
        " Kotlin ByteArray".encodeToByteArray()
    hexdump(data)
}

Output:

00000000  48 65 6c 6c 6f 2c 20 62 79 74 65 73 21 0a 00 01  |Hello, bytes!...|
00000010  ff 20 4b 6f 74 6c 69 6e 20 42 79 74 65 41 72 72  |. Kotlin ByteArr|
00000020  61 79                                            |ay|

Base64

Base64 encodes binary data as ASCII text, so it can travel in JSON, URLs, HTTP headers or emails. Kotlin's kotlin.io.encoding.Base64 is stable since 2.2 and works on all platforms (java.util.Base64 is the JVM-only alternative):

import kotlin.io.encoding.Base64

fun main() {
    val data = byteArrayOf(-5, -1, 0, 1, 2)
    val std = Base64.encode(data)
    val url = Base64.UrlSafe.encode(data)
    println(std)
    println(url)
    println(Base64.decode(std).contentToString())
    println(Base64.UrlSafe.decode(url).contentToString())

    val noPad = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT)
    println(noPad.encode("hi".encodeToByteArray()))
    println(Base64.encode("hi".encodeToByteArray()))

    try {
        Base64.decode("not base64!")
    } catch (e: IllegalArgumentException) {
        println("error: ${e.message}")
    }
}

Output:

+/8AAQI=
-_8AAQI=
[-5, -1, 0, 1, 2]
[-5, -1, 0, 1, 2]
aGk
aGk=
error: Invalid symbol ' '(40) at index 3

Base64 output is 4/3 of the input size, rounded up to a multiple of 4.

Bitwise operations

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

Java Kotlin
a & b a and b
a | b a or b
a ^ b a xor b
~a a.inv()
a << n a shl n
a >> n a shr n
a >>> n a ushr n
fun main() {
    val a = 0b1100
    val b = 0b1010
    println((a and b).toString(2))   // 1000
    println((a or b).toString(2))    // 1110
    println((a xor b).toString(2))   // 110
    println(a.inv())                 // -13
    println(1 shl 10)                // 1024
    println(-16 shr 2)               // -4, sign bit copied
    println(-16 ushr 28)             // 15, zeros shifted in

    val n = 0b1011_0000
    println(n.countOneBits())
    println(n.countTrailingZeroBits())
    println(n.takeHighestOneBit())
    println(0x12345678.rotateLeft(8).toHexString())
}

Output:

1000
1110
110
-13
1024
-4
15
3
4
128
34567812

Because these are ordinary infix functions, their precedence differs from Java's. All infix calls 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())   // (hi shl 8) or lo
    println((lo or hi shl 8).toHexString())   // (lo or hi) shl 8 -- not what Java does
    println(lo or (hi shl 8))
    println(1 shl 2 + 1)                      // 1 shl 3
    val flags = 0b0110
    println(flags and 0b0010 != 0)            // (flags and 0b0010) != 0
}

Output:

00001234
00003600
4660
8
true

In Java lo | hi << 8 means lo | (hi << 8). The same expression in Kotlin shifts the result of or. Add parentheses whenever you mix shifts with and/or.

The shift operators are defined only for Int and Long. Byte and Short get and, or, xor and inv from kotlin.experimental, but no shifts. Convert to Int first, and mask, or a negative byte will sign-extend:

import kotlin.experimental.and
import kotlin.experimental.inv

fun main() {
    val b: Byte = 0x96.toByte()   // 1001 0110
    val high = (b.toInt() shr 4) and 0x0F
    val low = b.toInt() and 0x0F
    println("$high $low")

    // Byte has and/or/xor/inv, but no shifts
    val masked: Byte = b and 0x0F
    println(masked)
    println(b.inv())

    // Wrong: shr on a negative byte sign-extends
    println(b.toInt() shr 4)
}

Output:

9 6
6
105
-7

Bit flags

Packing booleans into an Int is common in file formats and protocols:

const val READ = 1 shl 0
const val WRITE = 1 shl 1
const val EXEC = 1 shl 2

fun Int.has(flag: Int) = this and flag != 0
fun describe(p: Int) = buildString {
    append(if (p.has(READ)) 'r' else '-')
    append(if (p.has(WRITE)) 'w' else '-')
    append(if (p.has(EXEC)) 'x' else '-')
}

fun main() {
    var perms = READ or WRITE
    println(describe(perms))
    perms = perms or EXEC       // set
    println(describe(perms))
    perms = perms and WRITE.inv() // clear
    println(describe(perms))
    perms = perms xor READ      // toggle
    println(describe(perms))
}

Output:

rw-
rwx
r-x
--x

this and flag != 0 works because infix calls bind tighter than !=, but (this and flag) != 0 is easier to read. In application code (as opposed to binary formats) an EnumSet is usually more readable than bit flags.

Multi-byte integers and endianness

An Int takes 4 bytes. The order in which they are stored is the byte order or endianness:

Doing it by hand with shifts:

fun writeIntBE(buf: ByteArray, offset: Int, v: Int) {
    buf[offset] = (v ushr 24).toByte()
    buf[offset + 1] = (v ushr 16).toByte()
    buf[offset + 2] = (v ushr 8).toByte()
    buf[offset + 3] = v.toByte()
}

fun readIntBE(buf: ByteArray, offset: Int): Int =
    (buf[offset].toInt() and 0xFF shl 24) or
    (buf[offset + 1].toInt() and 0xFF shl 16) or
    (buf[offset + 2].toInt() and 0xFF shl 8) or
    (buf[offset + 3].toInt() and 0xFF)

fun readIntLE(buf: ByteArray, offset: Int): Int =
    (buf[offset].toInt() and 0xFF) or
    (buf[offset + 1].toInt() and 0xFF shl 8) or
    (buf[offset + 2].toInt() and 0xFF shl 16) or
    (buf[offset + 3].toInt() and 0xFF shl 24)

fun main() {
    val buf = ByteArray(4)
    writeIntBE(buf, 0, 0x0A0B0C0D)
    println(buf.toHexString())
    println(readIntBE(buf, 0).toHexString())
    println(readIntLE(buf, 0).toHexString())

    writeIntBE(buf, 0, -2)
    println(buf.toHexString())
    println(readIntBE(buf, 0))
}

Output:

0a0b0c0d
0a0b0c0d
0d0c0b0a
fffffffe
-2

toByte() keeps the low 8 bits, so no masking is needed when writing. When reading, and 0xFF is required: without it a byte like 0xFE becomes 0xFFFFFFFE after toInt() and its sign bits overwrite the other bytes when combined with or.

ByteBuffer

java.nio.ByteBuffer does the shifting for you and supports both byte orders. It has a position (where the next relative get/put happens) and a limit (the end of readable or writable data):

import java.nio.ByteBuffer
import java.nio.ByteOrder

fun main() {
    val buf = ByteBuffer.allocate(16)
    buf.putInt(0xCAFEBABE.toInt())
    buf.putShort(65)
    buf.put(7)
    buf.putDouble(1.5)
    println("position=${buf.position()} remaining=${buf.remaining()}")

    buf.flip()  // limit = position, position = 0: ready to read
    println(buf.getInt().toUInt().toString(16))
    println(buf.getShort())
    println(buf.get())
    println(buf.getDouble())
    println("remaining=${buf.remaining()}")

    val bytes = buf.array().copyOf(buf.limit())
    println(bytes.toHexString())

    val le = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(1).array()
    val be = ByteBuffer.allocate(4).putInt(1).array()
    println("LE ${le.toHexString()}  BE ${be.toHexString()}")
    println(ByteOrder.nativeOrder())
}

Output:

position=15 remaining=1
cafebabe
65
7
1.5
remaining=0
cafebabe0041073ff8000000000000
LE 01000000  BE 00000001
LITTLE_ENDIAN

Forgetting flip() between writing and reading is the classic ByteBuffer bug: you'd read from the current position, past the data you wrote.

ByteBuffer.wrap(bytes) creates a buffer over an existing array without copying. Combined with absolute getters like getInt(index), which don't move the position, it's a concise way to parse a fixed-layout header. Here's the header of a BMP image, which is little-endian:

import java.nio.ByteBuffer
import java.nio.ByteOrder

data class BmpInfo(val fileSize: Int, val dataOffset: Int, val width: Int, val height: Int, val bitsPerPixel: Int)

fun parseBmp(bytes: ByteArray): BmpInfo {
    require(bytes.size >= 30 && bytes[0] == 'B'.code.toByte() && bytes[1] == 'M'.code.toByte()) {
        "not a BMP file"
    }
    val b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
    return BmpInfo(
        fileSize = b.getInt(2),
        dataOffset = b.getInt(10),
        width = b.getInt(18),
        height = b.getInt(22),
        bitsPerPixel = b.getShort(28).toInt() and 0xFFFF,
    )
}

fun main() {
    // the first 30 bytes of a 2x2 24-bit BMP
    val header = "424d46000000000000003600000028000000020000000200000001001800".hexToByteArray()
    println(parseBmp(header))
}

Output:

BmpInfo(fileSize=70, dataOffset=54, width=2, height=2, bitsPerPixel=24)

In real code you'd get the bytes from Path("image.bmp").readBytes(). See Files and I/O for reading files and using ByteBuffer with FileChannel.

DataOutputStream and ByteArrayOutputStream

For variable-length data, a stream is more convenient than a fixed-size buffer. ByteArrayOutputStream is a growable byte array. DataOutputStream writes primitives in big-endian order and DataInputStream reads them back:

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream

data class Point(val id: Long, val name: String, val x: Float, val y: Float)

fun encode(points: List<Point>): ByteArray {
    val bos = ByteArrayOutputStream()
    DataOutputStream(bos).use { out ->
        out.writeInt(points.size)
        for (p in points) {
            out.writeLong(p.id)
            out.writeUTF(p.name)
            out.writeFloat(p.x)
            out.writeFloat(p.y)
        }
    }
    return bos.toByteArray()
}

fun decode(bytes: ByteArray): List<Point> =
    DataInputStream(ByteArrayInputStream(bytes)).use { inp ->
        List(inp.readInt()) {
            Point(inp.readLong(), inp.readUTF(), inp.readFloat(), inp.readFloat())
        }
    }

fun main() {
    val pts = listOf(Point(1, "origin", 0f, 0f), Point(2, "pt", 1.5f, -2f))
    val bytes = encode(pts)
    println("${bytes.size} bytes")
    println(bytes.toHexString(HexFormat { bytes { bytesPerLine = 16; byteSeparator = " " } }))
    println(decode(bytes))
}

Output:

48 bytes
00 00 00 02 00 00 00 00 00 00 00 01 00 06 6f 72
69 67 69 6e 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 02 00 02 70 74 3f c0 00 00 c0 00 00 00
[Point(id=1, name=origin, x=0.0, y=0.0), Point(id=2, name=pt, x=1.5, y=-2.0)]

writeUTF writes a 2-byte length followed by the string in a modified UTF-8 (00 06 then origin). It's fine for data your own program reads back, but to interoperate with other languages write the length and encodeToByteArray() bytes yourself. readInt() and friends throw EOFException if the data is truncated.

Replace ByteArrayOutputStream with Files.newOutputStream(path).buffered() to write the same format straight to a file. For structured data exchanged with other systems, consider an established format like Protocol Buffers or CBOR (kotlinx-serialization-cbor) instead of a hand-rolled one.

Checksums and hashes

A checksum detects accidental corruption. java.util.zip has CRC32, CRC32C and Adler32. Cryptographic hashes come from MessageDigest:

import java.security.MessageDigest
import java.util.zip.CRC32

fun main() {
    val data = "hello".encodeToByteArray()

    val crc = CRC32()
    crc.update(data)
    println(crc.value.toHexString())
    println(crc.value.toUInt().toHexString())

    var xor = 0
    for (b in data) xor = xor xor (b.toInt() and 0xFF)
    println(xor.toByte().toHexString())

    val sha = MessageDigest.getInstance("SHA-256").digest(data)
    println(sha.size)
    println(sha.toHexString())
}

Output:

000000003610a686
3610a686
62
32
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

CRC32.value is a Long holding a 32-bit unsigned value. Convert it with toUInt() (or toInt()) before formatting or storing it in 4 bytes. More on hashing and encryption in Cryptography.

Random bytes

import kotlin.random.Random
import java.security.SecureRandom

fun main() {
    val r = Random(42)
    println(r.nextBytes(8).toHexString())

    val key = ByteArray(16)
    SecureRandom().nextBytes(key)
    println(key.size)

    // wipe secrets after use
    key.fill(0)
    println(key.all { it == 0.toByte() })
}

Output:

1accef394020bf67
16
true

Seeded kotlin.random.Random is reproducible, which is good for test data. Use SecureRandom for keys, tokens and nonces. Keeping secrets in a ByteArray (rather than a String) lets you overwrite them with fill(0) when done. See Random numbers for more.

Common mistakes

Feedback about page:

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



Table Of Contents