javascript - 从字节缓冲区转换为字符串,然后在 NodeJS / Javascript 中转换回字节
问题描述
就像标题所述,我只是想在一个字符串中编码一些字节,然后将它们解码回字节。将 Uint8 字节数组转换为字符串然后再转换回数组并不完美。我只是想知道我应该在转换中使用什么编码以使其正确发生。
我试试这个作为一个虚拟的例子:
var bytes = serializeToBinary(); // giving me bytes
console.log('bytes type:'+ Object.prototype.toString.call(bytes));
console.log('bytes length:'+ bytes.length);
var bytesStr = bytes.toString('base64'); // gives me a string that looks like '45,80,114,98,97,68,111'
console.log('bytesStr length:'+ bytesStr.length);
console.log('bytesStr type:'+ Object.prototype.toString.call(bytesStr));
var decodedbytesStr = Buffer.from(bytesStr, 'base64');
console.log('decodedbytesStr type:'+ Object.prototype.toString.call(decodedbytesStr));
console.log('decodedbytesStr length:'+ decoded.length);
输出:
bytes type:[object Uint8Array]
bytes length:4235
bytesStr type:[object String]
bytesStr length:14161
decodedbytesStr type:[object Uint8Array]
decodedbytesStr length:7445
decodedbytesStr 长度和字节长度不应该相同吗?
解决方案
TypedArray
不支持.toString('base64')
。该base64
参数被忽略,您只需获得数组值的字符串表示形式,用逗号分隔。这不是base64 字符串,因此Buffer.from(bytesStr, 'base64')
没有正确处理它。
您想改为调用.toString('base64')
a Buffer
。创建时bytesStr
,只需Buffer
从您的Uint8Array
第一个开始构建:
var bytesStr = Buffer.from(bytes).toString('base64');
推荐阅读
- python - 遍历具有索引的列
- angular - 如何使用 Angular Material 在 Angular 8 中创建轮播?
- django - 应用 lestsencrypt 后,我的 nginx 服务器死了
- xamarin - Xamarin: Is there any way for my testers to download my app from AppCenter without the need to login to AppCenter First?
- android - tablayout 中的 recyclerview 只调用一次
- mongodb - docker-compose 中的 mongoimport 给我“无法启动服务”错误
- android - 尝试通过ARCORE在android native中实现Environmental HDR
- php - 如何从 Access 数据库中的表格数据生成在线报告?
- c# - C# - 布尔属性值不会改变:(
- r - 是否有可能有几个小时的滑块输入,可以选择从 22 点到凌晨 3 点的范围?