0

I have the following code to convert a binary to a hex in NodeJS:

const bin = "1011100100001011101010100011100100001001101000100011101110110101101111011000001111111100010010111110001110101011100111101101110101100110110111000001111010101010110001110001110000110101001111111101000100110011111000010111110011001011000000001001010000100100"
const hex = parseInt(bin, 2).toString(16).toUpperCase();
console.log(hex)

and it only return:

B90BAA3909A23800000000000000000000000000000000000000000000000000
2
  • 1
    Im not sure, but this could be possible a "out of range" error. I think the number/input that parseInt returns is to big/long.With a smaler input, it works. Commented Jul 31, 2021 at 13:12
  • 1
    I looked a the source from "rapidtables.com/convert/number/binary-to-hex.html" they use the "BigNumber" pacakge on npm. console.log((new BigNumber(bin, 2)).toString(16).toUpperCase()) Perhaps this works without "BigNumber" and instead of use developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 31, 2021 at 13:34

1 Answer 1

1

As maximum safe integer in JavaScript is just 2^53 - 1 or 0b11111111111111111111111111111111111111111111111111111 (see Number.MAX_SAFE_INTEGER), you need BigInt here:

const bigIntFromBin = BigInt("0b1011100100001011101010100011100100001001101000100011101110110101101111011000001111111100010010111110001110101011100111101101110101100110110111000001111010101010110001110001110000110101001111111101000100110011111000010111110011001011000000001001010000100100");
const bigIntHex = bigIntFromBin.toString(16).toUpperCase();
console.log(bigIntHex);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.