V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
youla
V2EX  ›  程序员

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

  •  
  •   youla · 2020-12-23 12:08:36 +08:00 · 1323 次点击
    这是一个创建于 1192 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 也翻遍了,鱼也摸过了。

    第 1 条附言  ·  2020-12-23 14:13:36 +08:00

    已解决!!!!!

    
    # 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)
    
    
    第 2 条附言  ·  2020-12-23 14:28:57 +08:00
    // 上面注释写错了,小尴尬 ; )
    
    KuroNekoFan
        1
    KuroNekoFan  
       2020-12-23 13:36:52 +08:00
    js 的 string to hex 只要 Number(`$hexString`)就可以了...
    KuroNekoFan
        2
    KuroNekoFan  
       2020-12-23 13:37:25 +08:00
    看错问题,忽略...
    dulife
        3
    dulife  
       2020-12-23 13:47:15 +08:00
    不慌,缩短 10cm 还剩 30cm
    GTim
        4
    GTim  
       2020-12-23 13:49:28 +08:00
    问题的关键在于你的编码,你后端返回的是 `gb2312`

    你可以尝试使用 `TextEncode` 和 `TextDecode` 试一试
    youla
        5
    youla  
    OP
       2020-12-23 13:58:04 +08:00
    @GTim 这个不是原生就有的吧。
    youla
        6
    youla  
    OP
       2020-12-23 14:14:20 +08:00
    @GTim 解决了,谢谢,不知道为什么之前没找到这个方法,我还以为要引用什么 library
    seki
        7
    seki  
       2020-12-23 14:30:30 +08:00
    如果不用兼容 ie 可以考虑用这个
    GTim
        8
    GTim  
       2020-12-23 14:48:16 +08:00
    @seki 都原生 websocket 了,这个方法肯定能用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3585 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:46 · PVG 12:46 · LAX 21:46 · JFK 00:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.