[TOC] #### 前言 --- 物聯(lián)網(wǎng)項目需要頻繁使用進制轉(zhuǎn)換,所以封裝了一些進制轉(zhuǎn)換函數(shù),本文記錄一下,方便以后使用 文本轉(zhuǎn)十六進制轉(zhuǎn)換器: [http://ascii-to-hex.bchrt.com](http://ascii-to-hex.bchrt.com) #### 1. 十進制轉(zhuǎn)為十六進制 --- ```javascript /** * 十進制轉(zhuǎn)為十六進制 * @param {Number} 十進制 */ function dec_to_hex(dec) { dec = Number(dec) let hex = dec.toString(16) return hex.length == 1 ? ('0' + hex) : hex } ``` #### 2. 十六進制轉(zhuǎn)為十進制 --- ```javascript /** * 十六進制轉(zhuǎn)為十進制 * @param {String} 十六進制 */ function hex_to_dec(hex) { hex = hex.toString() return parseInt(hex, 16) } ``` #### 3. 十六進制轉(zhuǎn)為二進制 --- ```javascript /** * 十六進制轉(zhuǎn)為二進制 * @param {String} 十六進制 */ function hex_to_bin(hex) { hex = hex.toString() return parseInt(hex, 16).toString(2) } ``` #### 4. 十六進制轉(zhuǎn)為 ASCII 字符 --- ```javascript /** * 十六進制轉(zhuǎn)為ascii字符 * @param {String} 十六進制字符 */ function hex_to_ascii(hex) { hex = hex.toString(); let str = ''; for (var n = 0; n < hex.length; n += 2) { str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); } return str; } ``` #### 5. 漢字轉(zhuǎn)為十六進制 --- ```javascript /** * 文字轉(zhuǎn)為十六進制 */ function words_to_hex(string) { let link = "" for (let i = 0; i < string.length; i++) { link += string.charCodeAt(i).toString(16) } return link } // 使用示例 const hex = words_to_hex('開發(fā)者') // 5f0053d18005 ```