* @returns {bigint|number} Decimal sum of the literal byte values
*/
toDec (bytes: Bytes): bigint | number {
- let decimal = 0n
+ let int = 0n
for (let i = bytes.byteLength; i > 0; i--) {
- decimal += BigInt(bytes[i - 1]) << (BigInt(bytes.byteLength - i) * 8n)
+ int += BigInt(bytes[i - 1]) << (BigInt(bytes.byteLength - i) << 3n)
}
- if (decimal > 9007199254740991n) {
- return decimal
+ if (int > 9007199254740991n) {
+ return int
} else {
- return Number(decimal)
+ return Number(int)
}
},
//! SPDX-FileCopyrightText: 2025 Chris Duncan <chris@codecow.com>
//! SPDX-License-Identifier: GPL-3.0-or-later
+import { HEXCHAR } from "../constants"
+
export const dec = Object.freeze({
/**
* Convert a decimal integer to a Uint8Array of bytes. Fractional part is
if (typeof padding !== 'number' || padding < 1 || padding > 0xffffffff) {
throw new TypeError('Invalid padding')
}
- let integer = BigInt(decimal)
- const bytes: number[] = (integer === 0n) ? [0] : []
- while (integer > 0) {
- const lsb = BigInt.asUintN(8, integer)
- bytes.push(Number(lsb))
- integer >>= 8n
+ let int = BigInt(decimal)
+ if (int < 0n) {
+ throw new TypeError('Decimal must be non-negative')
+ }
+ const bytes: number[] = (int === 0n) ? [0] : []
+ while (int > 0n) {
+ bytes.push(Number(int & 255n))
+ int >>= 8n
}
- const result = new Uint8Array(Math.max(padding, bytes.length))
+ const result = new Uint8Array(padding > bytes.length ? padding : bytes.length)
result.set(bytes)
return (result.reverse())
},
/**
- * Convert a decimal integer to a hexadecimal string.
+ * Convert a non-negative decimal integer to a hexadecimal string.
*
* @param {(bigint|number|string)} decimal - Integer to convert
* @param {number} [padding=1] - Minimum length of the resulting string padded as necessary with starting zeroes
if (typeof padding !== 'number' || padding < 1 || padding > 0x1fffffffe) {
throw new TypeError('Invalid padding')
}
- try {
- return BigInt(decimal)
- .toString(16)
- .padStart(padding, '0')
- .toUpperCase()
- } catch (err) {
- throw new RangeError('Invalid decimal integer')
+ let int = BigInt(decimal)
+ if (int < 0n) {
+ throw new TypeError('Decimal must be non-negative')
+ }
+ let hex: string = ''
+ while (int > 0n) {
+ hex = HEXCHAR[Number(int & 15n)] + hex
+ int >>= 4n
+ }
+ while (hex.length < padding) {
+ hex = '0' + hex
}
+ return hex
},
})