js字符串序列化为二进制数据

在JavaScript中,可以通过不同的方式将字符串序列化为二进制数据。以下是几种常见的方法:

  1. TextEncoder 和 TextDecoder
    JavaScript 提供了 TextEncoderTextDecoder 对象,可以用来处理字符串和二进制数据之间的转换。

    // 将字符串转换为二进制数据
    const encoder = new TextEncoder();
    const text = 'Hello, 你好!';
    const encoded = encoder.encode(text);
    
    // 将二进制数据解码为字符串
    const decoder = new TextDecoder();
    const decoded = decoder.decode(encoded);
    
    console.log(encoded); // Uint8Array(15) [72, 101, 108, 108, 111, 44, 32, 228, 189, 160, 229, 165, 189, 33]
    console.log(decoded); // Hello, 你好!
    

    这种方法可以处理 UTF-8 编码的字符串。

  2. TypedArray
    可以使用 TypedArray 来处理二进制数据,例如 Uint8Array

    // 将字符串转换为 Uint8Array
    const text = 'Hello, 你好!';
    const bytes = new Uint8Array(text.length);
    for (let i = 0; i < text.length; i++) {
        bytes[i] = text.charCodeAt(i);
    }
    
    console.log(bytes); // Uint8Array(15) [72, 101, 108, 108, 111, 44, 32, 203, 156, 229, 165, 189, 33]
    

    这种方法需要注意字符编码的处理,特别是非 ASCII 字符。

  3. 直接操作字符串的 UTF-16 编码
    JavaScript 中的字符串使用 UTF-16 编码,可以直接操作其编码单元(16 位)。

    // 将字符串转换为 UTF-16 编码
    const text = 'Hello, 你好!';
    const bytes = new Uint16Array(text.length);
    for (let i = 0; i < text.length; i++) {
        bytes[i] = text.charCodeAt(i);
    }
    
    console.log(bytes); // Uint16Array(8) [72, 101, 108, 108, 111, 44, 20320, 22909]
    

    这种方法比较底层,需要理解字符串的 UTF-16 编码方式。

根据具体的需求和场景,可以选择适合的方法将字符串序列化为二进制数据。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值