前几天遇到一个 js 文件,看起来就跟乱码似的,节选如下:
一番搜索后,发现这玩意儿 \x62
这种是 16 进制的表示方法。趁着这个机会,来理一理 js 中的进制转换问题吧。
js 进制转换
js 中进制转换经常用的两个函数是 toString
和 parseInt
toString
我们打开浏览器的 console 控制台
看例子:
(15).toString(); // 把 15 转换成10进制的表示形式
> 15
(15).toString(2); // 把 15 转换成2进制的表示形式
> 1111
(15).toString(8); // 把 15 转换成8进制的表示形式
> 17
(15).toString(16); // 把 15 转换成16进制的表示形式
> f
parseInt
在浏览器控制台输入下面的代码
parseInt("f", 16) // 把 f 按照 16 进制转换成 10 进制的表示形式
> 15
parseInt("17", 8) // 把 17 按照 8 进制转换成 10 进制的表示形式
> 15
parseInt("1111", 2) // 把 1111 按照 2 进制转换成 10 进制的表示形式
> 15
parseInt("15", 10)
> 15
parseInt
跟 toString
的转换正好是相反的。
字符编码
打开浏览器 console
"A".charCodeAt() // 也就是说 A 的内部编码值是 65
> 65
String.fromCharCode(65) // 65 这个编码值对应着字符 A
"A"
这里的 65 指的都是十进制的。
js 中二进制,八进制,十六进制表示
console.log(0x6D) // 十六进制 0x 开头
> 109
console.log(0155) // 八进制 0 开头
> 109
console.log(0b01101101) // 二进制 0b 开头
> 109
字符串转义
Character | Meaning |
---|---|
\0 | Null Byte |
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Tab |
\v | Vertical tab |
\’ | Apostrophe or single quote |
\” | Double quote |
\ | Backslash character |
\XXX | The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol. |
\xXX | The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol. |
\uXXXX | The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences. |
\u{XXXXX} | Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04. |
(以上摘自 Grammar_and_types#String_literals)
这下就清楚了,遇到 ‘\XXX’ 就按照八进制解码,遇到 ‘\xXX’ 就按照 16 进制解码。
比如:
console.log('\x64');
> d
免费工具
js 加密(混淆)防君子防不住小人的。如果我们只是想增加别人阅读的困难,用一些免费工具,混淆一下,变量名无意义了,就很难看懂了。免费混淆工具 javascriptobfuscator.com
解密工具 www.sojson.com