📅  最后修改于: 2023-12-03 15:16:04.583000             🧑  作者: Mango
在进行网络编程或是文件传输时,我们有时需要将 ASCII 码转换成十六进制表示。在 Javascript 中,可以使用 charCodeAt
和 toString
进行转换。
以下代码将字符串 "hello" 中的每个字符转换成相应的十六进制表示:
const str = "hello";
const hexList = [];
for (let i = 0; i < str.length; i++) {
const hex = str.charCodeAt(i).toString(16);
hexList.push(hex);
}
console.log(hexList.join(" "));
// Output: 68 65 6c 6c 6f
解析:
str
和一个空数组 hexList
,这个数组用于存放每个字符的十六进制表示;for
循环遍历字符串 str
中的每个字符;charCodeAt
方法获取字符的 ASCII 码,并使用 toString
方法将其转换成十六进制表示;hexList
数组中;以下代码将十六进制表示 "68 65 6c 6c 6f" 转换成相应的 ASCII 码:
const hexStr = "68 65 6c 6c 6f";
const asciiStr = hexStr
.split(" ")
.map(hex => String.fromCharCode(parseInt(hex, 16)))
.join("");
console.log(asciiStr);
// Output: hello
解析:
hexStr
;split
方法将字符串按空格分割成字符串数组;parseInt
方法将每个字符串解析成十六进制数,并使用 String.fromCharCode
方法将每个十六进制数转换成字符;以上就是在 Javascript 中将 ASCII 码转换成十六进制表示的方法,以及将十六进制表示转换成 ASCII 码的方法。希望对你有所帮助。