NodeJS 如何将Javascript缓冲区转换为仅包含0和1的字符串

ryoqjall  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(117)

所以我目前正在尝试实现霍夫曼alg,它在解码和编码方面工作得很好。但是,我存储编码后的数据如下。
编码函数的结果是一个包含许多由0和1组成的字符串的列表,所有字符串的长度都是可变的。
如果我把它们保存在一个普通的txt文件中,它会占用更多的空间,如果我把它们存储在二进制文件中,例如,一个代码为101的“e”将被存储在一个完整的8位中,看起来像“00000101”,这是浪费的,不会占用比原始txt文件更少的存储空间。我把列表中的所有字符串放到一个字符串中,并把它分成长度为8的相等部分,以便更有效地存储它们。
然而,如果我想现在读取数据,而不是0和1,我会得到UTF-8字符,甚至一些转义字符。
我用fs.readFileSync("./encoded.bin", "binary");阅读文件,但是javascript认为它已经是一个缓冲区,并将其转换为字符串,这一切都变得很奇怪...有什么解决方案或想法将其转换回0和1吗?
我也试着把fs.readFileSync("./encoded.bin", "binary");中的“二进制”转换成“utf-8”,这有助于不使我的终端崩溃,但仍然是“#C_C_C_Y_Kf_g〈_e_t”。
为了澄清,我的目标是最终读出大量的二进制数据串,看起来像“00011001000101001010”,并实际上将其转换为字符串...

6xfqseft

6xfqseft1#

您可以使用Number.parseInt(str, 2)1 s和0 s的String转换为字节的数字表示,若要将其转换回来,您可以使用nr.toString(2)
整个过程看起来如下所示:

const original = '0000010100000111';
// Split the string in 8 char long substrings
const stringBytes = original.match(/.{8}/g);
// Convert the 8 char long strings to numerical byte representations
const numBytes = stringBytes.map((s) => Number.parseInt(s, 2));
// Convert the numbers to an ArrayBuffer
const buffer = Uint8Array.from(numBytes);
// Write to file

// Read from file and reverse the process
const decoded = [...buffer].map((b) => b.toString(2).padStart(8, '0')).join('');

console.log('original', original, 'decoded', decoded, 'same', original === decoded);
s5a0g9ez

s5a0g9ez2#

var binary = fs.readFileSync("./binary.bin");
binary = [...binary].map((b) => b.toString(2).padStart(8, "0")).join("");
console.log(binary);

//Output will be like 010000111011010

相关问题