DEV Community

Discussion on: Explain JS's radix in parseInt(str, radix), like I'm five.

Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited

It's used when converting between number systems.

I have some code with it here when I made a script to convert between ASCII, Hexidecimal, and Binary for me since I needed to do that often for a cryptography class.

To go from hex to decimal to ASCII, I did this:

case 'hex': {
        input.forEach(function(hex) {
          if (hex[0] == 0 && hex[1] == 'x') {
            hex = hex.slice(2);
          }

          return String.fromCharCode(parseInt(hex, 16)) + ' ';
        });
      }

and to go from binary to decimal to ASCII, this:

      case 'binary': {
        input.forEach(function(binary) {
          return String.fromCharCode(parseInt(binary, 2)) + ' ';
        });
      }

Since hex numbers are in base 16, you need to tell parseInt to interpret a base 16 number. Or binary numbers are in a base 2 system, so radix is 2. If you don't provide a radix, it just defaults to 10 since that's what the "main" number system is.