bigint.js 599 B

1234567891011121314
  1. import { toHex, fromHex } from '@exodus/bytes/hex.js'
  2. import { assert } from './fallback/_utils.js'
  3. const _0n = BigInt(0)
  4. export function fromBigInt(x, { length, format } = {}) {
  5. assert(Number.isSafeInteger(length) && length > 0, 'Expected length arg to be a positive integer')
  6. assert(typeof x === 'bigint' && x >= _0n, 'Expected a non-negative bigint')
  7. const hex = x.toString(16)
  8. assert(length * 2 >= hex.length, `Can not fit supplied number into ${length} bytes`)
  9. return fromHex(hex.padStart(length * 2, '0'), format)
  10. }
  11. export const toBigInt = (a) => BigInt('0x' + (toHex(a) || '0'))