• 请不要在回答技术问题时复制粘贴 AI 生成的内容
youla
V2EX  ›  程序员

js string to hex 有哪些需要注意的地方?

  •  
  •   youla · Dec 23, 2020 · 2713 views
    This topic created in 2140 days ago, the information mentioned may be changed or developed.

    img0

    用 c#写了一个感觉挺简单,毕竟封装得很无脑了。

    js 写的话完全没头绪...(好吧,其实就是懒)

    因为接收到的数据 arrayBuffer

    var ws = new WebSocket("ws://localhost:8899");
    ws.binaryType = "arraybuffer";
    ……
    ws.send("看到这行字的人,鸡鸡缩短 10cm");
    ……
    ws.onmessage = (e) =>{
        var blob = new Blob([new Uint8Array(e.data)]);
        var reader = new FileReader();
        reader.onload = (evt) => {
            console.log(reader.result);
        };
        reader.readAsText(blob, "GB2312");
    }
    
    //这样转字符串不会乱码
    

    现在纠结是 arrayBuffer to hex ?? blob to hex ?? string to hex ??

    找到的 js string to hex function 基本都是英文没什么问题,但是中文我将收获一段乱码?

    怎么转才不会出现乱码呢?

    stackoverflow 都翻遍了,jsdelivr 也翻遍了,鱼也摸过了。

    Supplement 1  ·  Dec 23, 2020

    已解决!!!!!

    
    # https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex
    
    var array = new TextEncoder().encode('你好啊')
    
    function buf2hex(buffer) { // buffer is an ArrayBuffer
      return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
    }
    
    buf2hex(array)
    
    
    Supplement 2  ·  Dec 23, 2020
    // 上面注释写错了,小尴尬 ; )
    
    KuroNekoFan
    KuroNekoFan
    Dec 23, 2020
    1
    js 的 string to hex 只要 Number(`$hexString`)就可以了...
    KuroNekoFan
    KuroNekoFan
    Dec 23, 2020
    2
    看错问题,忽略...
    dulife
    dulife
    Dec 23, 2020
    3
    不慌,缩短 10cm 还剩 30cm
    yemoluo
    yemoluo
    Dec 23, 2020
    4
    问题的关键在于你的编码,你后端返回的是 `gb2312`

    你可以尝试使用 `TextEncode` 和 `TextDecode` 试一试
    youla
    youla
    OP
    Dec 23, 2020
    5
    @GTim 这个不是原生就有的吧。
    youla
    youla
    OP
    Dec 23, 2020
    6
    @GTim 解决了,谢谢,不知道为什么之前没找到这个方法,我还以为要引用什么 library
    seki
    seki
    Dec 23, 2020
    7
    如果不用兼容 ie 可以考虑用这个
    yemoluo
    yemoluo
    Dec 23, 2020
    8
    @seki 都原生 websocket 了,这个方法肯定能用
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2825 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:33 · PVG 08:33 · LAX 16:33 · JFK 19:33
    ♥ Do have faith in what you're doing.