Skip to content

Instantly share code, notes, and snippets.

@Fantasim
Last active February 7, 2021 09:39
Show Gist options
  • Save Fantasim/e586e0f1c054668b40c539565c189518 to your computer and use it in GitHub Desktop.
Save Fantasim/e586e0f1c054668b40c539565c189518 to your computer and use it in GitHub Desktop.
BigInt to bytes array in TS
const TWO = BigInt(2)
const ONE = BigInt(1)
const ZERO = BigInt(0)
const MINUS = BigInt(-1)
const MAX_UINT_8 = BigInt(256)
const MAX_UINT_16 = BigInt(65536)
const MAX_UINT_32 = BigInt(4294967296)
const MAX_UINT_64 = BigInt(18446744073709551616)
const intToByteArray = (val: BigInt, valType: 'int8' | 'int16' | 'int32' | 'int64', isUnsigned: boolean) => {
const M = {'int8': MAX_UINT_8, 'int16': MAX_UINT_16, 'int32': MAX_UINT_32, 'int64': MAX_UINT_64}[valType]
const N_BYTE = {'int8': 8, 'int16': 16, 'int32': 32, 'int64': 64}[valType]
const CURRENT_MIN_INT = (M / TWO) * MINUS
const CURRENT_MAX_INT = (M / TWO) - ONE
if (!isUnsigned && (val < CURRENT_MIN_INT || val > CURRENT_MAX_INT)){
throw new Error("overflow")
} else if (isUnsigned && (val < ZERO || val > ((CURRENT_MAX_INT * TWO) + ONE))){
throw new Error("unsigned overflow")
}
if (val < ZERO) {
val = ((CURRENT_MAX_INT+ONE) * TWO) + BigInt(val)
}
let binary = val.toString(2);
const length = N_BYTE - binary.length
for (var i = 0; i < length; i++){
binary = `0${binary}`
}
var ret = new Uint8Array(binary.length / 8)
i = 0;
while (i < binary.length){
ret[(binary.length / 8) - 1 - i] = parseInt(binary.substr(i, 8), 2)
i += 8
}
return ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment