From c9f9a676972abefb2744955dca99e384c9a80d0d Mon Sep 17 00:00:00 2001 From: "alexander.nutz" Date: Mon, 25 Mar 2024 11:46:59 +0100 Subject: [PATCH] decode int from bytes --- build.gradle.kts | 2 +- src/main/kotlin/blitz/Endian.kt | 38 ++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 8619a98..5517be4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,7 +5,7 @@ plugins { } group = "me.alex_s168" -version = "0.2" +version = "0.3" repositories { mavenCentral() diff --git a/src/main/kotlin/blitz/Endian.kt b/src/main/kotlin/blitz/Endian.kt index 6bd3212..edb2c6b 100644 --- a/src/main/kotlin/blitz/Endian.kt +++ b/src/main/kotlin/blitz/Endian.kt @@ -1,5 +1,8 @@ package blitz +import java.nio.ByteBuffer +import java.nio.ByteOrder + enum class Endian { LITTLE, BIG @@ -8,8 +11,15 @@ enum class Endian { infix fun encodeLittle(little: ByteArray) = if (this == BIG) little.reversedArray() else little + + fun toNIO(): ByteOrder = + if (this == LITTLE) ByteOrder.LITTLE_ENDIAN + else ByteOrder.BIG_ENDIAN } +fun ByteBuffer.order(endian: Endian): ByteBuffer = + order(endian.toNIO()) + fun Long.toBytes(endian: Endian) = endian encodeLittle toInt().toBytes(Endian.LITTLE) + @@ -36,4 +46,30 @@ fun Byte.toBytes() = byteArrayOf(this) fun UByte.toBytes() = - toByte().toBytes() \ No newline at end of file + toByte().toBytes() + +// TODO: no cheat + +fun ByteArray.toShort(endian: Endian) = + ByteBuffer.wrap(this).order(endian).getShort() + +fun ByteArray.toUShort(endian: Endian) = + toShort(endian).toUShort() + +fun ByteArray.toInt(endian: Endian) = + ByteBuffer.wrap(this).order(endian).getInt() + +fun ByteArray.toUInt(endian: Endian) = + toInt(endian).toUInt() + +fun ByteArray.toLong(endian: Endian) = + ByteBuffer.wrap(this).order(endian).getLong() + +fun ByteArray.toULong(endian: Endian) = + toLong(endian).toULong() + +fun ByteArray.toByte() = + this[0] + +fun ByteArray.toUByte() = + this[0].toUByte() \ No newline at end of file