ref #35 bitwise pack/unpack for integers

This commit is contained in:
Sergey Chernov 2025-07-11 06:09:09 +03:00
parent 987b80e44d
commit d969993997
3 changed files with 27 additions and 4 deletions

View File

@ -47,6 +47,10 @@ abstract class BitInput {
return getBitsOrNull(count) ?: throw IllegalStateException("Unexpected end of stream") return getBitsOrNull(count) ?: throw IllegalStateException("Unexpected end of stream")
} }
fun getBit(): Int {
return getBitOrNull() ?: throw IllegalStateException("Unexpected end of stream")
}
fun unpackUnsigned(): ULong { fun unpackUnsigned(): ULong {
val tetrades = getBits(4).toInt() val tetrades = getBits(4).toInt()
var result = 0UL var result = 0UL
@ -57,5 +61,11 @@ abstract class BitInput {
} }
return result return result
} }
fun unpackSigned(): Long {
val isNegative = getBit()
val value = unpackUnsigned().toLong()
return if( isNegative == 1) -value else value
}
} }

View File

@ -45,7 +45,7 @@ abstract class BitOutput {
} }
@Suppress("unused") @Suppress("unused")
fun putSigned(value: Long) { fun packSigned(value: Long) {
if( value < 0 ) { if( value < 0 ) {
putBit(1) putBit(1)
packUnsigned((-value).toULong()) packUnsigned((-value).toULong())

View File

@ -37,13 +37,26 @@ class LynonTests {
} }
@Test @Test
fun testPackInteger() { fun testUnsignedPackInteger() {
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
bout.packUnsigned(147179UL) bout.packUnsigned(1471792UL)
bout.close() bout.close()
println(bout.toUByteArray().toDump()) println(bout.toUByteArray().toDump())
val bin = MemoryBitInput(bout.toUByteArray()) val bin = MemoryBitInput(bout.toUByteArray())
assertEquals(147179UL, bin.unpackUnsigned()) assertEquals(1471792UL, bin.unpackUnsigned())
}
@Test
fun testSignedPackInteger() {
val bout = MemoryBitOutput()
bout.packSigned(-1471792L)
bout.packSigned(1471792L)
// bout.packSigned(147179L)
bout.close()
println(bout.toUByteArray().toDump())
val bin = MemoryBitInput(bout.toUByteArray())
assertEquals(-1471792L, bin.unpackSigned())
assertEquals(1471792L, bin.unpackSigned())
} }
} }