Created
March 30, 2023 08:22
-
-
Save mrpapercut/69de88533256eab12a7098847893c242 to your computer and use it in GitHub Desktop.
Javascript bitstring to BigInt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bitstringToBigInt = bstr => { | |
let counter = 0n; | |
let byteindex = 0n; | |
for (let i = bstr.length - 1; i >= 0; i--) { | |
if (bstr[i] === '1') { | |
counter += 2n**byteindex; | |
} | |
byteindex++; | |
} | |
return counter; | |
} | |
const bitstring16 = '10101000000000001'; | |
const expected16 = 86017n; | |
const bitstring64 = '10000000000000000000000000000000000000000000001000000000010000001'; | |
const expected64 = 18446744073709813889n; | |
const bitstring500 = '100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000001'; | |
const expected500 = 3273390607896141870013189696827599152216642046043064789483291368096133796404674554883271737830461478356928839096742628359722239281751026650784062242817n; | |
console.log(bitstringToBigInt(bitstring16), bitstringToBigInt(bitstring16) === expected16); | |
console.log(bitstringToBigInt(bitstring64), bitstringToBigInt(bitstring64) === expected64); | |
console.log(bitstringToBigInt(bitstring500), bitstringToBigInt(bitstring500) === expected500); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment