gpt4 book ai didi

c++ - 将字节转换为位并将二进制数据写入文件

转载 作者:行者123 更新时间:2023-11-30 04:05:39 29 4
gpt4 key购买 nike

假设我有一个字符数组,char a[8],其中包含 10101010。如果我将此数据存储在 .txt 文件中,则此文件大小为 8 个字节。现在我想知道如何将此数据转换为二进制格式并将其保存为 8 位(而不是 8 字节)的文件,以便文件大小仅为 1 字节。

此外,一旦我将这 8 个字节转换为一个字节,我应该将输出保存为哪种文件格式? .txt 或 .dat 或 .bin?

我正在研究文本文件的霍夫曼编码。我已经将文本格式转换为二进制格式,即 0 和 1,但是当我将此输出数据存储在文件中时,每个数字(1 或 0)占用一个字节而不是一个位。我想要一个解决方案,使每个数字只需要一点。

char buf[100];
void build_code(node n, char *s, int len)
{
static char *out = buf;
if (n->c) {
s[len] = 0;
strcpy(out, s);
code[n->c] = out;
out += len + 1;
return;
}

s[len] = '0'; build_code(n->left, s, len + 1);
s[len] = '1'; build_code(n->right, s, len + 1);
}

这就是我在霍夫曼树的帮助下构建我的代码树的方式。和

void encode(const char *s, char *out)
{
while (*s)
{
strcpy(out, code[*s]);
out += strlen(code[*s++]);
}
}

这就是我编码以获得最终输出的方式。

最佳答案

不完全确定你如何最终得到一个表示值的二进制表示的字符串,但您可以使用标准函数(如 std::strtoul)从字符串(任何基数)中获取整数值.

该函数提供一个无符号长整型值,因为您知道您的值在 0-255 范围内,您可以将它存储在一个无符号字符中:

无符号字符 v=(无符号字符)(std::strtoul(binary_string_value.c_str(),0,2) & 0xff);

写入磁盘,可以使用ofstream来写入

Which File format should I save the output in? .txt or .dat or .bin?

请记住,扩展名(.txt、.dat 或 .bin)并不真正规定格式(即内容的结构)。扩展名是一种约定通常用于指示您正在使用某种众所周知的格式(并且在某些操作系统/环境中,它驱动配置哪个程序最能处理该文件)。由于这是您的文件,因此由您定义实际格式......并使用您最喜欢的任何扩展名(甚至没有扩展名)命名文件(或者换句话说,最能代表您的内容的任何扩展名)作为只要它对您和那些将使用您的文件的人有意义。

编辑:附加细节

假设我们有一个长度为“0”和“1”的缓冲区

int codeSize; // size of the code buffer
char *code; // code array/pointer
std::ofstream file; // File stream where we're writing to.


unsigned char *byteArray=new unsigned char[codeSize/8+(codeSize%8+=0)?1:0]
int bytes=0;
for(int i=8;i<codeSize;i+=8) {
std::string binstring(code[i-8],8); // create a temp string from the slice of the code
byteArray[bytes++]=(unsigned char)(std::strtoul(binstring.c_str(),0,2) & 0xff);
}

if(i>codeSize) {
// At this point, if there's a number of bits not multiple of 8,
// there are some bits that have not
// been writter. Not sure how you would like to handle it.
// One option is to assume that bits with 0 up to
// the next multiple of 8... but it all depends on what you're representing.
}

file.write(byteArray,bytes);

关于c++ - 将字节转换为位并将二进制数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23209360/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com