Convert a string to a decimal base using JavaScript

  • 2020-03-30 03:57:18
  • OfStack

JS is a very magical language, the internal system of many functions can help us to carry out number (base) conversion;

JS can directly use hexadecimal;
Var a = 0 XFF. / / 255

Convert any hexadecimal string to decimal, such as binary, octal, hexadecimal, the second number is not written is the most commonly used conversion to integer decimal;


parseInt("11", 2); //3, 2 to 10
parseInt("77", 8); //Hexadecimal to hexadecimal
parseInt("af", 16); //175 hexadecimal to hexadecimal

Converts hexadecimal to binary, octal, and hexadecimal strings
Object. ToString (n) : can (n) represent the base, such as


(152).toString(2) //"10011000"; Convert 152 into an object using parentheses, or write it as follows. < br / > 152..toString(2) //Here the first point converts 152 to a decimal of the float type, and the second point is the eject object method; < br / > 152..toString(16) //"98" : decimal to hexadecimal
152..toString(32) //"4o" : decimal to 32

If necessary during the conversion process. You can use the following:


/**
* @param num It needs to be made up 16 For the digital
* @param len The number of digits to fill Here is the
* @returns The completed string
* */
function format(num, len) {
var l = num.length;
if (num.length < len) {
for (var i = 0; i < len - l; i++) {
num = "0" + num;
}
}
return num;
}


Related articles: