js 字符串转十六进制utf-8 十六进制utf-8转字符串

43 阅读1分钟

//字符串转十六进制utf-8

function stringToHexUTF8(str) {
    const encoder = new TextEncoder() // 创建一个TextEncoder实例
    const view = encoder.encode(str) // 将字符串编码为UTF-8编码的Uint8Array
    let hexStr = ''
    for (let i = 0; i < view.length; i++) {
        hexStr += view[i].toString(16).padStart(2, '0') // 将每个字节转换为十六进制并补齐
    }
    return hexStr
}

let hexStr = stringToHexUTF8('0x@34%黑神话悟空')

console.log(hexStr)

//十六进制utf-8转字符串

function hexToBytes(hexString) {
    let bytes = new Uint8Array(hexString.length / 2)
    for (let i = 0; i < bytes.length; i++) {
        bytes[i] = parseInt(hexString.substr(i * 2, 2), 16)
    }
    return bytes
}

function hexToUtf8String(hexString) {
    let bytes = hexToBytes(hexString)
    let decoder = new TextDecoder('utf-8')
    return decoder.decode(bytes)
}

let utf8String = hexToUtf8String('307840333425e9bb91e7a59ee8af9de6829fe7a9ba')

console.log( utf8String)