refactor encodings
This commit is contained in:
@@ -49,40 +49,24 @@ internal class BigInt private constructor(
|
||||
}
|
||||
|
||||
fun toByteArray(): ByteArray {
|
||||
val msw = words.last()
|
||||
val mswBytes = when {
|
||||
(msw ushr 24) != 0 -> 4
|
||||
(msw ushr 16) != 0 -> 3
|
||||
(msw ushr 8) != 0 -> 2
|
||||
else -> 1
|
||||
val bytes = ByteArray((words.size * 4) - words.last().countLeadingZeroBytes())
|
||||
for (i in bytes.indices) {
|
||||
val (wi, bi) = (bytes.lastIndex - i).divRem(4)
|
||||
bytes[i] = (words[wi] ushr (bi * 8)).toByte()
|
||||
}
|
||||
val size = ((words.size - 1) * 4) + mswBytes
|
||||
val result = ByteArray(size)
|
||||
|
||||
for (i in 0..<size) {
|
||||
val index = size - 1 - i
|
||||
val shift = (index % 4) * 8
|
||||
result[i] = (words[index / 4] ushr shift).toByte()
|
||||
}
|
||||
|
||||
return result
|
||||
return bytes
|
||||
}
|
||||
|
||||
companion object {
|
||||
val zero: BigInt
|
||||
get() = BigInt(intArrayOf(0))
|
||||
|
||||
fun from(value: ByteArray): BigInt {
|
||||
val size = value.size.divCeil(4)
|
||||
val words = IntArray(size)
|
||||
|
||||
for (i in value.indices) {
|
||||
val byte = value[i].toInt() and 0xFF
|
||||
val index = value.lastIndex - i
|
||||
val shift = (index % 4) * 8
|
||||
words[index / 4] = words[index / 4] or (byte shl shift)
|
||||
fun from(bytes: ByteArray): BigInt {
|
||||
val words = IntArray(bytes.size.divCeil(4))
|
||||
for (i in bytes.indices) {
|
||||
val (wi, bi) = (bytes.lastIndex - i).divRem(4)
|
||||
words[wi] = words[wi] or ((bytes[i].toInt() and 0xFF) shl (bi * 8))
|
||||
}
|
||||
|
||||
return BigInt(words)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user