一、16進制轉string在線
現在,我們可以在網上找到很多免費的16進制轉字符串的在線工具。只需將16進制代碼複製並粘貼到文本框中,單擊“轉換”按鈕即可得到結果。 這些在線工具的好處是速度非常快,並且在大多數情況下,工作非常可靠。讓我們看一下下面的代碼,使用以上效果:
function hex_to_ascii(str1) { var hex = str1.toString(); var str = ''; for (var n = 0; n < hex.length; n += 2) { str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); } return str; } console.log(hex_to_ascii('313233')); // 輸出123
二、16進制轉10進制計算公式
我們都知道,每個16進制數字都有出現在所述位置的權值。其中’F’的權值最大,最小的是’0’。因此,可以通過使用以下公式將16進制數字轉換為其等效的10進制數:
Hex Value = F * 16 ^ 15 + F * 16 ^ 14 + E * 16 ^ 13 + ….. + 0 * 16 ^ 0
三、16進制轉String
有兩種方法可以將16進制數字轉換為字符串。其中一種方法是使用標準JavaScript函數String.fromCharCode。這個函數接受一個數字,返回其ASCII等效項。因此,我們可以將16進制數字的十進制值傳遞給該函數來轉換為字符串。以下是相應的代碼:
var hex = '4f'; console.log(String.fromCharCode(parseInt(hex, 16))); // 輸出O
另一種方法是使用JavaScript編碼方式,如下所示:
var hex = "4f"; var str = ""; for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); console.log(str); // 輸出O
四、16進制轉換器
我們可以使用現成的16進制轉換器來快速執行16進制到其他進制的轉換,如二進制,八進制或十進制。這些轉換器將自動執行轉換並顯示結果。以下是一個典型的16進制轉換器的示例:
function hexToDec(hexString) { return parseInt(hexString, 16); } function hexToBin(hexString) { var dec = hexToDec(hexString); return dec.toString(2); } function hexToOct(hexString) { var dec = hexToDec(hexString); return dec.toString(8); } console.log(hexToDec("7F")); // 輸出127 console.log(hexToBin("7F")); // 輸出1111111 console.log(hexToOct("7F")); // 輸出177
五、16進制轉二進制表
我們可以使用以下代碼將16進制轉換為二進制表:
function hexToBinTable(hex) { var bin = parseInt(hex, 16).toString(2), pad = bin.length % 4; if (pad > 0) { bin = "0".repeat(4 - pad) + bin; } return bin.match(/.{4}/g).join(" "); } console.log(hexToBinTable("1F")); // 輸出0001 1111
六、16進制轉10進制的公式
有一個簡單的公式可以將16進制數轉換為10進制數。該公式為:
10進制值= dcba (16 ^ 0) + ihgf(16 ^ 1)+ [nmlk(16 ^ 2)+……]
在此公式中,d,c,b,a是16進制數的最低位,g,f,e,d是中間位,k,j,m,n是最高位。以下是將16進制數轉換為10進制的完整代碼:
function hexToDec(hex) { return parseInt(hex, 16); } console.log(hexToDec("7F")); // 輸出127
七、16進制轉2進制
要將16進制數轉換為二進制數,請將16進制數轉換為10進制數,然後將10進制數轉換為二進制數。以下是將16進制數轉換為二進制數的代碼(使用上面定義的hexToDec函數):
function hexToBin(hex) { var dec = hexToDec(hex); return dec.toString(2); } console.log(hexToBin("7F")); // 輸出111111
八、16進制轉2進制計算器
使用下面的代碼來將16進制轉換為二進制的計算器:
var h2b = { "0":"0000", "1":"0001", "2":"0010", "3":"0011", "4":"0100", "5":"0101", "6":"0110", "7":"0111", "8":"1000", "9":"1001", "A":"1010", "B":"1011", "C":"1100", "D":"1101", "E":"1110", "F":"1111" }; function hexToBinCalculator(hex) { var bin = ""; for (var i = 0; i < hex.length; i++) { bin += h2b[hex.charAt(i)]; } return bin; } console.log(hexToBinCalculator("7F")); // 輸出111111
結語
這裡我們詳細介紹了16進制轉換為string的各種方法。無論您正在處理什麼類型的項目,這些技術都非常有用,因此務必記下這些技巧。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/155064.html