ref #35 bitwise pack/unpack for integers
This commit is contained in:
parent
987b80e44d
commit
d969993997
@ -47,6 +47,10 @@ abstract class BitInput {
|
||||
return getBitsOrNull(count) ?: throw IllegalStateException("Unexpected end of stream")
|
||||
}
|
||||
|
||||
fun getBit(): Int {
|
||||
return getBitOrNull() ?: throw IllegalStateException("Unexpected end of stream")
|
||||
}
|
||||
|
||||
fun unpackUnsigned(): ULong {
|
||||
val tetrades = getBits(4).toInt()
|
||||
var result = 0UL
|
||||
@ -57,5 +61,11 @@ abstract class BitInput {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun unpackSigned(): Long {
|
||||
val isNegative = getBit()
|
||||
val value = unpackUnsigned().toLong()
|
||||
return if( isNegative == 1) -value else value
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,7 +45,7 @@ abstract class BitOutput {
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun putSigned(value: Long) {
|
||||
fun packSigned(value: Long) {
|
||||
if( value < 0 ) {
|
||||
putBit(1)
|
||||
packUnsigned((-value).toULong())
|
||||
|
@ -37,13 +37,26 @@ class LynonTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testPackInteger() {
|
||||
fun testUnsignedPackInteger() {
|
||||
val bout = MemoryBitOutput()
|
||||
bout.packUnsigned(147179UL)
|
||||
bout.packUnsigned(1471792UL)
|
||||
bout.close()
|
||||
println(bout.toUByteArray().toDump())
|
||||
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())
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user