Skip to content

Instantly share code, notes, and snippets.

@mrenouf
Last active August 22, 2026 15:04
Show Gist options
  • Select an option

  • Save mrenouf/7cd7ac6cb4875ea18f33090e3f54cca4 to your computer and use it in GitHub Desktop.

Select an option

Save mrenouf/7cd7ac6cb4875ea18f33090e3f54cca4 to your computer and use it in GitHub Desktop.
Varint Encoding
fun writeVarint(long: Long) {
require(long >= 0) { "Varint must be non-negative" }
var v = long
while (v and 0x7fL.inv() != 0L) {
writeByte(((v and 0x7fL) or 0x80L).toByte())
v = v ushr 7
}
writeByte((v and 0x7fL).toByte())
}
fun readVarint(): Long {
var result = 0L
var shift = 0
while(true) {
val byte = readByte().toLong()
result = result or ((byte and 0x7fL) shl shift)
if (byte and 0x80L == 0L) break
shift += 7
if (shift > 63) {
throw IllegalArgumentException("Invalid varint value: overflow while decoding")
}
}
return result
}
fun writeByte(value: Byte)
fun readByte(): Byte
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment