所以我目前正在尝试实现霍夫曼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”,并实际上将其转换为字符串...
2条答案
按热度按时间6xfqseft1#
您可以使用
Number.parseInt(str, 2)
将1
s和0
s的String
转换为字节的数字表示,若要将其转换回来,您可以使用nr.toString(2)
。整个过程看起来如下所示:
s5a0g9ez2#