How to proper convert ULong to ByteArray and vice-versa?

If I had to deal with Long I’d create the following extension:

    fun Long.toByteArray(): ByteArray {
        val buffer = ByteBuffer.allocate(Long.SIZE_BYTES)
        buffer.putLong(this)
        return buffer.array()
    }

I wonder what the proper way to convert usigned int and long to big endian in this case since ByteBuffer obviously don’t accept them.

Just do: unsignedLong.toLong().toByteArray().

Long and ULong are very similar things. They just differ in the way how they interpret the value with most-significant bit set to 1. As long as you handle the data as unsigned both when writing and reading to/from binary, everything should be fine.

1 Like