Scoop API

scoop:scoop.math:0.1.0

src/internal/integer/binary_text.scoop

Selected production source · src/internal/integer/binary_text.scoop

1package scoop.math
3internal fun radixBitWidth(radix: Int): Long = when (radix) {
4 case 2 -> 1L
5 case 4 -> 2L
6 case 8 -> 3L
7 case 16 -> 4L
8 case 32 -> 5L
9 case _ -> 0L
12// Power-of-two radices pack digits directly, including groups that cross a limb boundary.
13internal fun integerParseBinaryRadix(text: String, radix: Int, width: Long): IntegerStorage? {
14 val chars = text.toCharArray()
15 if (chars.size == 0L) return None
16 val negative = chars[0L] == '-'
17 val start = if (negative || chars[0L] == '+') 1L else 0L
18 if (start == chars.size) return None
19 var first = chars.size
20 var index = start
21 while (index < chars.size) {
22 val digit = mathDigit(chars[index])
23 if (digit < 0 || digit >= radix) return None
24 if (digit != 0 && first == chars.size) first = index
25 index += 1L
26 }
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.size
32 var bit = 0L
33 while (index > first) {
34 index -= 1L
35 val digit = mathDigit(chars[index]).toUInt()
36 val offset = bit % 32L
37 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 += width
41 }
42 return Some(integerFromMagnitude(negative, words.toArray()))
45internal 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 0L
50 return String.fromChars(Array<Char>(addExact(digits, sign)) { position ->
51 if (position < sign) '-'
52 else {
53 val bit = (digits - 1L - (position - sign)) * width
54 val offset = bit % 32L
55 val high = if (offset + width > 32L) magnitudeWord(words, bit / 32L + 1L) shl (32L - offset) else 0u
56 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 })