将字符写为C++字节
Writing chars as a byte in C++
我正在用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
完全相同。
编辑:哦,你想为字节中的位写一个1
和0
字符序列。C++有一个晦涩难懂的技巧:
#include <bitset>
tempfile << std::bitset< 8 >( tempnode->ch );
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 在UNIX系统中使用DIR查找文件的字节大小
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- std::当在256字节边界上写入整数时,流的奇怪行为
- 当比特(而不是字节)的顺序至关重要时的持久性
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 字节到位运算符重载C++
- 在java中读取c++字节的位字段
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 字节真的是最小可寻址单元吗
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- 如何使用 OpenCV 解码在两个 UWP 应用之间发送的图像字节?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 如何将原始字节附加到 std::vector?
- 基于字节数组生成静态范围整数值