preface
See more and more recently the interview questions are handwritten algorithm or hand code implements some functions, I am interested to do, but found that there is a problem, to the realization of js hexadecimal conversion online answer really is too little, and this is also the basis of a part of the students is weak, so a handwritten implementation, help you lu qing conversion between hexadecimal
Using built-in functions
When it comes to base conversions, we must first mention the two built-in methods toString and parseInt in JS; ToString converts a number to a specified base. ParseInt is a number parsed to decimal in a specified base.
//toString, where 0 before a number defaults to base 8, and 0x to base 16.
var = 10;
(10).toString(2); / / output "1010"
(10).toString(16); / / output "A"
(010).toString(10); / / output "8"
(0x10).toString(10); / / output "16"
Copy the code
/ / parseInt usage
parseInt("10".2); / / return 2
parseInt("10".8); / / return 8
parseInt("10".10); / / return 10
parseInt("AF".16); / / back to 175
Copy the code
Handwritten implementation
If we’re going to write it by hand, we’re going to have to figure it out in code. For the sake of convenience, we substitute ** from ES6 for Math.pow(radix, I) to represent the relationship between exponents. For example, using 8 to represent how many powers of 2, you can get Math.pow(2,3) === 2**3 in one of two ways
We know js native toString method, can convert the base, base minimum is 2, the maximum is 36, because Arabic digits plus English letters is 0-9,A-Z just add up to 36, most use these letters to represent the number of base composition. Base map table for. Var who = ‘0123456789 abcdefghijklmnopqrstuvwxyz’;
(10).toString(2) // Return "1010" => 2**3*1 + 2**2*0 + 2**1*1 + 2**0*0
(1234).toString(10) / / return "1234" = > 10 * * 3 * 1 + 10 * * 2 * 2 + 10 * 10 * * 1 * 3 + 0 * 4
(110).toString(16) Return "6e" => 16**1*6 + 16*0*14. Where 14 comes from digits[14]
Copy the code
Important: the number in front of the top => can be expressed by the expression after the =>.Copy the code
For example to convert 10 to base 2, first we can calculate how many powers 10 comes closest to 2, it should be 8, expressed in power math.pow (radix, I), where the radix is 2, I is 3,8 binary is 1000,8 is 2 less than 10, 2 is expressed in base 2 as 10, so it adds up to 1010.
So the idea of all numbers in decimal arithmetic can be expressed as radix** I *rate + radix**(I -1)*rate2 + radix**(I -2)*rate3... ; / / "1234" = > 10 * * 3 * 1 + 10 * * 2 * 2 + 10 * 10 * * 1 * 3 + 0 * 4 why conversion can get the above expression, because the addition of power is always greater than 2 * * * * 2 + 2 3 > = 2. So it's always decreasing. It's important to understand this step.Copy the code
function to_string(num,radix){ // Convert a decimal number to the base of the argument
if(num == 0) return num;
if(!Number.isInteger(num)){// Mice are not currently supported
console.warn('Decimal conversion is not currently supported');
return ;
}
var res = ' ',rate,i;
if(num < 0) {// Handle negative numbers
res += The '-'
num = Math.abs(num)
}
// In order to get the highest power, for example, 110 is converted to hexadecimal 6e, where I is 1; So that's 1 out of 16 times 1 times 6;
// Get the highest power in order to calculate the multiples of each digit and corresponding characters from the power below
for(i = 0; i<num; i++){if(Math.pow(radix,i) <= num && Math.pow(radix,i+1) > num){
break; }}// Start fetching the resulting character based on the highest power, i.e., the power +1 character
while(i>=0){
rate = Math.floor(num/Math.pow(radix,i));// Get a multiple of the highest power
res += digits[rate]; // For example, if 110 to hexadecimal is 6e, the first rate is 6,digits[6] === 6, the second rate is 14,digits[14] === e; So res added up twice is 6e;
num -= rate * Math.pow(radix,i); // Since the highest digit has been counted, subtract the highest digit already counted. Let's move on to the next calculation
i--;
}
return res;
}
// Parse a number to decimal based on the passed argument.
function parse_int(str,radix){
str = (str+' ').toUpperCase();
var res = 0,abs = 1,len = str.length,i;
if(str[0= = =The '-') {// Handle negative numbers
abs = -1;
str=str.substring(1)}for(i = len - 1; i >=0; i--){
res += digits.indexOf(str[len-1-i]) * Math.pow(radix,i)
}
return abs*res;
}
function convert_radix(str,source_radix,to_radix){ To_radix radix radix radix radix radix radix
return to_string(parse_int(str,source_radix),to_radix)
}
Copy the code
By the convert_radix method, a number can be converted from the source base to the target base. For example convert_radix(‘1011’, 2, 10) gives 11.
To convert decimal to another base, call the to_string method, such as to_string(10,2) to get 1010.
Converting other bases to decimal calls parse_int, such as parse_int(‘6e’,16) to 110.
Base implementation is written by myself, no reference, so there is performance optimization or better scheme, more advice.