Skip to content

Instantly share code, notes, and snippets.

@L-Briand
Last active October 27, 2022 18:15
Show Gist options
  • Save L-Briand/78c1fd504eeabd101f3cd0bfe6e41707 to your computer and use it in GitHub Desktop.
Save L-Briand/78c1fd504eeabd101f3cd0bfe6e41707 to your computer and use it in GitHub Desktop.
private inline fun <R> ByteArray.reduce(
offset: Int, size: Int, default: R,
reducer: (acc: R, element: Byte, offsetIdx: Int) -> R
): R {
var acc = default
val upperBound = offset + size
if (0 > offset && upperBound >= size) throw RuntimeException("Selected range not in bound. ${offset until upperBound} !in $indices")
for (i in offset until upperBound) {
acc = reducer(acc, get(i), i - offset)
}
return acc
}
fun Long.toByteArray() = ByteArray(Long.SIZE_BYTES) { ((this shr (8 * it)) and 0xFF).toByte() }
fun ByteArray.toLong(at: Int) = reduce(at, Long.SIZE_BYTES, 0L) { acc, element, offsetIdx ->
acc or ((element.toLong() and 0xFF) shl (offsetIdx * 8))
}
inline fun Int.toByteArray() = ByteArray(Int.SIZE_BYTES) { ((this shr (8 * it)) and 0xFF).toByte() }
inline fun ByteArray.decodeInt(at: Int = 0) = reduce(at, Int.SIZE_BYTES, 0) { acc, element, offsetIdx ->
acc or ((element.toInt() and 0xFF) shl (offsetIdx * 8))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment