[Daily knowledge] Hexadecimal conversion: binary, octal, hexadecimal

foreword

In JavaScript, we can be divided into two types:

basic type;

complex type;

The difference between the two types is: the storage location is different.

1. Basic type

Undefined, Null, Number, Boolean, String and Symbol (symbol, new in es6)

2. Complex types

Object

In ECMAScript, all values ​​can be represented by one of the above seven data types.


What we are talking about today is Number in the basic data type

Number

The most common integer type format for values ​​is decimal, and octal (starting with zero), hexadecimal (starting with 0x) can also be set

1. Decimal

Decimal integers are the most basic numeric literals, which can be written directly:

let Num = 22 // 10进制的22

2. Octal

The prefix is ​​0, and then the corresponding octal number is connected, usually 0~7.

If the number in the literal exceeds the expected range, the leading 0 will be ignored, and the following sequence of numbers will be treated as a decimal number.

let num1 = 026 // 8进制的22
let num2 = 081 // 无效 变为10进制

How to convert octal to decimal:

Hundreds digit × 8 to the 2nd power + tens digit × 8 to the 1st power + units digit × 8 to the 0th power =  decimal

For example: num1=026; converted to decimal is: 0 × 8² + 2 × 8¹ + 6 × 8º = 22

  • Except 0, any number raised to the power of 0 is equal to 1
  • Octal values ​​in ECMAScript 2015 or ES6 are represented by the prefix 0o; in strict mode, the prefix 0 is considered a syntax error, and if you want to represent an octal value, you should use the prefix 0o

3. Hexadecimal

Prefixed with 0x (case sensitive), hexadecimal digits are 0 ~ 9 and A ~ F.

The binary numbers represented by ABCDEF are: 10, 11, 12, 13, 14, 15

let Num1 = 0x1A //16进制的26

Calculation method of converting hexadecimal to decimal:

Hundreds digit × 16 to the 2nd power + tens digit × 16 to the 1st power + units digit × 16 to the 0th power =  decimal

For example: Num1=0x1A; converted to decimal is: 1 × 16¹ + 10 × 16º = 16 + 10= 26

4. Binary

The value is only 0 and 1, and the representation of binary literals is added in es6, starting with 0b

let num5 = 0b101 //2进制的5
let num6 = 0b111001 //2进制的57

Binary to decimal calculation method:

... Hundreds digit × 2 to the 2nd power + tens digit × 2 to the 1st power + units digit × 2 to the 0th power =  decimal

Such as: num6=0b111001; converted to decimal is: 57

A base converter is recommended here, which can be converted into the base you want

base converter

Guess you like

Origin blog.csdn.net/qq_46580087/article/details/125905813