Home >Web Front-end >JS Tutorial >Using JavaScript to perform hexadecimal conversion
JS is a very magical language, with many built-in functions that can help us convert numbers;
Hexadecimal can be used directly in JS;
var a = 0xff; //255
Convert any base string to decimal, such as binary, octal, hexadecimal, the second digit is most commonly converted to integer decimal without writing it;
parseInt("11", 2) ; // 3 Convert binary to decimal
parseInt("77", 8); // 63 Convert octal to decimal
parseInt("af", 16); //175 Convert hexadecimal to decimal System
Convert decimal to binary, octal, hexadecimal string
Object.toString(n): (n) represents the base, such as
(152).toString( 2) // "10011000" ; First use parentheses to convert 152 into an object, or write it as follows;
152..toString(2) // The first point here converts 152 into a float type decimal, and the The two points are to introduce the object method;
152..toString(16) // "98": Convert decimal to hexadecimal
152..toString(32) // "4o": Convert decimal to hexadecimal
Similarly, the maximum base supported by Javascript is 36 (26 English letters + 10 numbers)
35..toString(36) // "z": supports the maximum encoding "Z", not case sensitive
If it needs to be completed during the conversion process. You can use the following method:
/**
* @param num The 16 digits that need to be completed
* @param len The number of digits that need to be completed Here is
* @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;
}