JS implements the sample code of decimal conversion to hexadecimal

JS implements the sample code of decimal conversion to hexadecimal

Preface

When we write code, we occasionally encounter the problem of base conversion. Common conversions include binary, octal, decimal, and hexadecimal, but hexadecimal is rarely heard of. Here, let's use JS to simply try to implement hexadecimal.

think

The structure of hexadecimal numbers

Before we begin, we need to first understand the composition of hexadecimal numbers so that we can have a clear understanding of hexadecimal numbers and the subsequent conversion of numbers. We all know that hexadecimal numbers are composed of characters from 0 to 9 and a to a. So what about hexadecimal numbers? , push af back 20 places, and it is obvious that its letter part is composed of 26 English letters az, so the hexadecimal number is composed of 0-9, az

Numerical preparation

After understanding its composition, start thinking, how can a decimal number be transformed into a hexadecimal number? We need to first prepare a "warehouse" array with 36 values. This array is used to store all the values ​​of hexadecimal numbers. When a decimal number needs to be converted, the value of the hexadecimal number is taken out of the warehouse according to the value. In the warehouse, 0-9 represents 0-9 of the hexadecimal number, and 10-35 represents az of the hexadecimal number. The code is as follows

function getNums36() {
  var nums36 = [];
  for(var i = 0; i < 36 ; i++) {
    if(i >= 0 && i <= 9) { // Store the values ​​0-9 nums36.push(i) 
    } else { // Store the value of az nums36.push(String.fromCharCode(i + 87)); // ASCII code conversion }
  }
  console.log(nums36,'--------'); // Check the value of the warehouse return nums36; 
}

accomplish

After the warehouse is built, we begin the process of decomposing the binary conversion.

  • First, the decimal number passed in is tested, and the floating-point number is judged first. Since the base conversion of floating-point numbers is not discussed here, it is returned directly. Secondly, negative numbers are detected and processed. If n is a negative number, the Math.abs() method is called to convert n into a positive number.
  • After the detection is completed, the conversion begins

Set up a while loop. First, perform modulo 36 on the value of n to get res.

var res = n % 36;

Here we need to get the lowest bit value of the decimal number converted to hexadecimal, throw res into the warehouse, get the corresponding hexadecimal value, and use unshift to store it in the first bit of arr.

arr.unshift(nums36[res]);

After processing the lowest bit, we need to carry the number and process the value of the higher bit.

n = parseInt(n/36);

At this point, a cycle is completed

We use while to continuously take the modulus of res on n and carry it continuously. Finally, we can convert the decimal number into a hexadecimal number.

Note that at this time, remember to add the negative number judgment of neg set previously to the first place

arr.unshift(neg)

Finally, return the hexadecimal number

return arr.join("");

Code

// Provide 36-bit expression 0-9 az
function getNums36() {
  var nums36 = [];
  for(var i = 0; i < 36 ; i++) {
    if(i >= 0 && i <= 9) {
      nums36.push(i)
    } else {
      nums36.push(String.fromCharCode(i + 87));
    }
  }
  return nums36;
}
function scale36(n) {
  // Single function // Hexadecimal number: 0-9 af Hexadecimal number: 0-9 az   
  const arr = [];
  var nums36 = getNums36();
  // 36 10
  if(!Number.isInteger(n)){//Floating point number judgment, currently does not support mice console.warn('decimal conversion is not supported');
    return n;
  } 
  var neg = '';
  if(n < 0){//Processing of negative numbers neg = '-';
      n = Math.abs(n)
  }
  while(n) {
    var res = n % 36;
    console.log(res,'++++++++');
    arr.unshift(nums36[res]);
    // Carry n = parseInt(n/36);
    console.log(n,'---------');
  }
  arr.unshift(neg)
  return arr.join("");

}

console.log(scale36(20)); // 10

Extensions

Implementation of 7-base numbers

This template is also applicable to the conversion of decimal to other bases. We only need to modify the value of the warehouse. Here we take a 7-base problem of LeetCode as an example

504. Base 7 Given an integer, convert it to base 7 and output it as a string.

Example 1:
Input: 100 Output: "202"

First prepare the 7-base numerical warehouse

function getNums7() {
  var nums7 = [];
  for(var i = 0; i < 7 ; i++) {
    
      nums7.push(i)
   
  }
  return nums7;
}

Then modify the remainder value and carry to complete the template reuse.

var res = n % 7;
n = parseInt(n/7);

Code function getNums7() {
  var nums7 = [];
  for(var i = 0; i < 7 ; i++) {
    
      nums7.push(i)
   
  }
  return nums7;
}
var convertToBase7 = function(num) {
  // Single function const arr = [];
  var nums7 = getNums7();
  var neg = '';
  if(num < 0){//Processing of negative numbers neg = '-';
      num = Math.abs(num)
  }
  if(num == 0) {
      return num + "";
  }
  
  while(num) {
    var res = num % 7; // intercept the high-order data arr.unshift(nums7[res]);  
    // Carry num = parseInt(num/7); 
  }
  arr.unshift(neg);
  return arr.join("");

}

summary

From this example, we can see that with a little modification, we can easily convert the decimal system to other systems. The key lies in the modulo of res and the construction of the warehouse value. By continuously carrying and while looping, we can finally get the number we want.

This is the end of this article about JS implementing decimal to hexadecimal conversion. For more relevant content about JS implementing decimal to hexadecimal conversion, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • PHP implementation of hexadecimal and decimal conversion function example

<<:  MySQL 5.0.96 for Windows x86 32-bit green simplified version installation tutorial

>>:  Centos7.4 server installation of apache and solutions to problems encountered during the installation process

Recommend

Detailed explanation of Mysql function call optimization

Table of contents Function call optimization Func...

Using iframe techniques to obtain visitor QQ implementation ideas and sample code

Today at work, a friend I added temporarily asked ...

How to display TIF format images in browser

The browser displays TIF format images Copy code T...

Implementation of IP address configuration in Centos7.5

1. Before configuring the IP address, first use i...

Solve the problem of specifying udp port number in docker

When Docker starts a container, it specifies the ...

JavaScript to dynamically load and delete tables

This article shares the specific code of JavaScri...

Summary of several implementations of returning to the top in HTML pages

Recently, I need to make a back-to-top button whe...

Nginx uses Lua+Redis to dynamically block IP

1. Background In our daily website maintenance, w...

Solution to CSS anchor positioning being blocked by the top fixed navigation bar

Many websites have a navigation bar fixed at the ...

A brief understanding of the three uses of standard SQL update statements

1. Environment: MySQL-5.0.41-win32 Windows XP Pro...

MySQL green decompression version installation and configuration steps

Steps: 1. Install MySQL database 1. Download the ...

Solution to the welcome to emergency mode message when booting CentOS7.4

Today I used a virtual machine to do an experimen...