javascript - 将缓冲区转换为字符串

标签 javascript react-native buffer

我正在尝试使用 Buffer.from 和 .toString() 将元标记转换为纯文本。我的目标是在主函数中使用 .map 方法显示关键字数组。但我注意到一些奇怪的行为。我的 map 功能无法正确显示关键字。

关键字:[79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110 , 0, 59, 0]

const buffer = Buffer.from(Keywords);

缓冲区: {"数据": [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110 , 0, 59, 0], "类型": "缓冲区"}

const bufferString = buffer.toString();

bufferString:Obst;Person;

将 bufferString 返回到我的主方法后: Set {"O", "", "b", "s", "t", ";", "P", "e", "r ”、“o”、“n”}

我也尝试过使用.split() const Words = bufferString.split(";"); => ["Obst", "Person", ""] 但是当我返回这个数组时,我的 map 函数仅显示第一个关键字中的字母 O,而不显示第二个关键字中的字母。

奇怪的是,当我创建一个像 let keywords = ["Obst", "Person", ""]; 这样的新数组时,一切都正常工作。

所以来自缓冲区的字符串一定有些奇怪。

最佳答案

UCS-2 is a character encoding standard in which characters are represented by a fixed-length 16 bits (2 bytes)

使用已知的编码,您可以正确解码并按预期获取数据:

const data = [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110, 0, 59, 0]
const dataBuffer = Buffer.from(data)
const utf16Decoder = new TextDecoder('UTF-16')

console.log(utf16Decoder.decode(dataBuffer)) // Obst;Person;

我认为它默认尝试解码为 utf8,并对每个字符之间不可渲染的空字节感到不安:

enter image description here

关于javascript - 将缓冲区转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74969221/

相关文章:

javascript - 使用 javascript 选择不同组中的所有单选按钮

javascript - React useEffect 仅从对象数组中获取最后一个元素

javascript - 如何从 React Native 中的两个数组中提取不相同的元素?

ssl - 从 NSInputStream 转换字节有问题吗?

Python 字符串先进先出

javascript - 浏览器端是否有任何 EventEmitter 在 nodejs 中具有类似的逻辑?

javascript - 简单的 jQuery droppable 不工作

javascript - 运行时 android 上的白色空白屏幕 react native

arrays - Node.js:创建 8 字节缓冲区

javascript - 根据您向下滚动页面的距离更改 div