11

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?

dakab
  • 4,878
  • 8
  • 40
  • 60
Go Go lu
  • 163
  • 1
  • 1
  • 9

2 Answers2

18

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

rsjaffe
  • 5,300
  • 7
  • 25
  • 36
11

Just add toUpperCase():

var hexa = parseInt(number, 2).toString(16).toUpperCase();
Lukasz Czerwinski
  • 11,373
  • 9
  • 50
  • 63
  • what if it is supposed to be a lowercase and then gets turned into the uppercase? – Ramen_Lover912 Feb 27 '20 at 07:46
  • 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: https://stackoverflow.com/a/55681265/3366464 – Gertjan Franken Apr 03 '20 at 07:54