scoop:scoop.math:0.1.0
src/internal/integer/binary_text.scoop
Selected production source · src/internal/integer/binary_text.scoop
1
package scoop.math3
internal fun radixBitWidth(radix: Int): Long = when (radix) {4
case 2 -> 1L5
case 4 -> 2L6
case 8 -> 3L7
case 16 -> 4L8
case 32 -> 5L9
case _ -> 0L10
}12
// Power-of-two radices pack digits directly, including groups that cross a limb boundary.13
internal fun integerParseBinaryRadix(text: String, radix: Int, width: Long): IntegerStorage? {14
val chars = text.toCharArray()15
if (chars.size == 0L) return None16
val negative = chars[0L] == '-'17
val start = if (negative || chars[0L] == '+') 1L else 0L18
if (start == chars.size) return None19
var first = chars.size20
var index = start21
while (index < chars.size) {22
val digit = mathDigit(chars[index])23
if (digit < 0 || digit >= radix) return None24
if (digit != 0 && first == chars.size) first = index25
index += 1L26
}27
if (first == chars.size) return Some(IntegerStorage.Small(0L))28
val topBits = 32L - wordLeadingZeros(mathDigit(chars[first]).toUInt())29
val bits = addExact(multiplyExact(chars.size - first - 1L, width), topBits)30
val words = MutableArray<UInt>(bits / 32L + (if (bits % 32L == 0L) 0L else 1L)) { _ -> 0u }31
index = chars.size32
var bit = 0L33
while (index > first) {34
index -= 1L35
val digit = mathDigit(chars[index]).toUInt()36
val offset = bit % 32L37
words[bit / 32L] = words[bit / 32L] or (digit shl offset)38
if (offset + width > 32L && bit / 32L + 1L < words.size)39
words[bit / 32L + 1L] = words[bit / 32L + 1L] or (digit shr (32L - offset))40
if (index > first) bit += width41
}42
return Some(integerFromMagnitude(negative, words.toArray()))43
}45
internal fun integerBinaryRadixString(value: IntegerStorage, radix: Int, width: Long): String {46
val words = integerMagnitude(value)47
val bits = magnitudeBits(words)48
val digits = bits / width + (if (bits % width == 0L) 0L else 1L)49
val sign = if (integerSign(value) < 0) 1L else 0L50
return String.fromChars(Array<Char>(addExact(digits, sign)) { position ->51
if (position < sign) '-'52
else {53
val bit = (digits - 1L - (position - sign)) * width54
val offset = bit % 32L55
val high = if (offset + width > 32L) magnitudeWord(words, bit / 32L + 1L) shl (32L - offset) else 0u56
val digit = ((magnitudeWord(words, bit / 32L) shr offset) or high) and (radix - 1).toUInt()57
(if (digit < 10u) digit.toInt() + 48 else digit.toInt() + 87).toChar()58
}59
})60
}