将字符写为C++字节

Writing chars as a byte in C++

本文关键字:C++ 字节 字符      更新时间:2023-10-16

我正在用C++编写一个霍夫曼编码程序,并使用此网站作为参考:

http://algs4.cs.princeton.edu/55compression/Huffman.java.html

我现在使用的是 writeTrie 方法,这是我的版本:

// write bitstring-encoded tree to standard output
void writeTree(struct node *tempnode){
if(isLeaf(*tempnode)){
    tempfile << "1";
    fprintf(stderr, "writing 1 to filen");
    tempfile << tempnode->ch;
    //tempfile.write(&tempnode->ch,1);
    return;
}
else{
    tempfile << "0";
    fprintf(stderr, "writing 0 to filen");
    writeTree(tempnode->left);
    writeTree(tempnode->right);
}   
}

看看注释的行 - 假设我正在写入一个文本文件,但我想在 tempnode->ch 写入构成字符的字节(这是一个无符号的字符,顺便说一句)。 关于如何做到这一点的任何建议? 注释的行给出了从无符号字符*到常量字符*的无效转换错误。

提前感谢!

编辑:澄清一下:例如,我希望我的最终文本文件是二进制的 - 只有1和0。如果你看一下我提供的链接的标题,他们给出了一个"ABRACADABRA!"和由此产生的压缩的例子。我想取字符(例如在上面的"A"示例中),使用它的无符号整数 (A='65'),并以二进制形式写入 65 作为字节。

字符与字节相同。前面的行tempfile << tempnode->ch;已经完全符合您的要求。

unsigned char没有超载的write,但如果你愿意,你可以做

tempfile.write(reinterpret_cast< char * >( &tempnode->ch ),1);

这相当丑陋,但它的作用与tempfile << tempnode->ch完全相同。

编辑:哦,你想为字节中的位写一个10字符序列。C++有一个晦涩难懂的技巧:

#include <bitset>
tempfile << std::bitset< 8 >( tempnode->ch );