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")
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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())
|
||||||
|
@ -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())
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user