在NodeJS/Javascript中从字节缓冲区转换为字符串,然后再转换回字节
与标题状态一样,我只是尝试将一些字节编码为字符串,然后将它们解码回字节。将Uint8字节数组转换为字符串,然后再转换回数组的过程并不完美。我只是想知道在转换过程中应该使用什么样的编码才能正确地进行转换 我尝试将此作为一个虚拟示例:在NodeJS/Javascript中从字节缓冲区转换为字符串,然后再转换回字节,javascript,arrays,string,encoding,Javascript,Arrays,String,Encoding,与标题状态一样,我只是尝试将一些字节编码为字符串,然后将它们解码回字节。将Uint8字节数组转换为字符串,然后再转换回数组的过程并不完美。我只是想知道在转换过程中应该使用什么样的编码才能正确地进行转换 我尝试将此作为一个虚拟示例: var bytes = serializeToBinary(); // giving me bytes console.log('bytes type:'+ Object.prototype.toString.call(bytes)); console.
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长度和字节长度不应该相同吗?
类型Darray
不支持.toString('base64')
。忽略base64
参数,只需获取数组值的字符串表示形式,用逗号分隔即可。这不是base64字符串,因此Buffer.from(bytesStr,'base64')
无法正确处理它
您想在缓冲区上调用.toString('base64')
。创建bytesStr
时,只需从Uint8Array
首先构建一个缓冲区
:
var bytesStr = Buffer.from(bytes).toString('base64');
@ah997n我自己犯了更愚蠢的错误<代码>:)
不客气。