普通字符串转换为 HEX(十六进制)字符串

1、使用 Buffer

用于 Node.js 环境

const str = "test123";

const hexStr = Buffer.from(str, "utf8").toString("hex");

console.log(hexStr);
# 输出结果

74657374313233
2、使用 charCodeAt

用于浏览器环境与 Node.js 环境

const str = "test123";

let hexStr = "";

for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    hexStr += charCode.toString(16).padStart(2, "0");
}

console.log(hexStr);
# 输出结果

74657374313233
3、使用 TextEncoder + Array.from

用于浏览器环境与 Node.js 环境

const str = "test123";

const encoder = new TextEncoder();
const bytes = encoder.encode(str);

const hexStr = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");

console.log(hexStr);
# 输出结果

74657374313233

封装成函数

1、使用 Buffer
function strToHexStr(str) {
    const hexStr = Buffer.from(str, "utf8").toString("hex");
    return hexStr;
}
const str = "test123";

const hexStr = strToHexStr(str);

console.log(hexStr);
# 输出结果

74657374313233
2、使用 charCodeAt
function strToHexStr(str) {
    let hexStr = "";
    for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        hexStr += charCode.toString(16).padStart(2, "0");
    }
    return hexStr;
}
const str = "test123";

const hexStr = strToHexStr(str);

console.log(hexStr);
# 输出结果

74657374313233
3、使用 TextEncoder + Array.from
function strToHexStr(str) {
    const encoder = new TextEncoder();
    const bytes = encoder.encode(str);
    const hexStr = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
    return hexStr;
}
const str = "test123";

const hexStr = strToHexStr(str);

console.log(hexStr);
# 输出结果

74657374313233
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐