How to implement base conversion in JavaScript: 1. Use the parseInt() function, the syntax "parseInt (value, the base of the value to be parsed)"; 2. Use the toString() function, the syntax "decimal number. toString (the base to be converted)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. parseInt()
parseInt: Convert a string into an integer
parseInt(<em>string</em>, <em>radix</em>)
Optional. Represents the base of the number to be parsed. The value is between 2 ~ 36.
If this parameter is omitted or its value is 0, the number will be parsed in base 10.
If it starts with "0x" or "0X", it will be base 16.
If the parameter is less than 2 or greater than 36, parseInt() will return NaN.
2. toString()
toString() method belongs to the Object
object, and many built-in objects in JavaScript are I wrote this function to achieve more suitable functional needs for myself.
Type | Behavior description |
---|---|
Array | Convert each element of Array as strings, and concatenate them one after another, using commas as separators between the two elements for splicing. |
Boolean | If the Boolean value is true, returns "true". Otherwise return "false". |
Date | Returns the textual representation of the date. |
Error | Returns a string containing relevant error information. |
Function | Returns a string in the following format, where functionname is the name of a function, and the toString method of this function is called: "function functionname() { [native code] }" |
#Number | Returns the string representation of the value. It can also return a string expressed in the specified base, please refer to Number.toString(). |
String | Returns the value of the String object. |
Object (default) | Returns "[object ObjectName]", where ObjectName is the name of the object type. |
//十进制转其他进制 var x=110; alert(x); alert(x.toString(2)); alert(x.toString(8)); alert(x.toString(32)); alert(x.toString(16)); //其他转十进制 var x='110'; alert(parseInt(x,2)); //6 =>以2进制解析110 alert(parseInt(x,8)); //72 =>以8进制解析110 alert(parseInt(x,16)); //272 =>以16进制解析110 //其他转其他 //先用parseInt转成十进制再用toString转到目标进制 alert(String.fromCharCode(parseInt(141,8))) alert(parseInt('ff',16).toString(2));
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to implement hexadecimal conversion in JavaScript. For more information, please follow other related articles on the PHP Chinese website!