13

I am converting binary to hexadecimal but the code below returns a wrong answer:

var number = 1011;
var hexa = parseInt(number, 2).toString(16);
return hexa;

This returns b but it should have to be return B. What is the problem?

3
  • 2
    parseInt(number , 2).toString(16).toUpperCase(); Apr 12, 2016 at 3:11
  • 4
    Hexadecimal can be lowercase
    – Nick Zuber
    Apr 12, 2016 at 3:12
  • 1
    Thanks Arun and Nick.
    – Go Go lu
    Apr 12, 2016 at 3:15

2 Answers 2

20

'b' is correct. Hexadecimal doesn't specify letter case, and many write hex strings with lower-case letters.

0
12

Just add toUpperCase():

var hexa = parseInt(number, 2).toString(16).toUpperCase();
2
  • what if it is supposed to be a lowercase and then gets turned into the uppercase? Feb 27, 2020 at 7:46
  • 1
    Note that you might lose information when converting big numbers this way, due to the limited precision of integers. If you need a higher level of precision, this solution leveraging BigInt might help: stackoverflow.com/a/55681265/3366464 Apr 3, 2020 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.