写入4位用的ofstream二进制文件 [英] Writing 4 bits to a binary file with ofstream
本文介绍了写入4位用的ofstream二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有0之间的无符号整数 - 16,我想将其写入到一个二进制文件,而不整个字节写入,如何将一个移位位来实现它。
0-16意味着我只需要4位,所以我应该能够存储在一个字节右2不同的数字?
以下code写入1号1个字节:
的std :: ofstream的文件;
file.open(TEST.bin,烧写的std :: IOS ::二进制|性病:: IOS ::出来);
焦炭oneByteNum =(char)的fourByteNum; //一些4字节的整数转换为1字节字符
file.write(安培; oneByteNum,sizeof的(炭));
使用bitshifts,我如何能实现2个数字为1字节?
我想读一些出字节将是一个相似的,反两个步骤呢?
解决方案
字符oneByteWithTwoNums =(oneByteNum1<< 4)+(oneByteNum2&安培;为0x0F);
If I have an unsigned integer between 0 - 16 and I want to write it to a binary file without writing a whole byte to it, how would one shift bits to achieve it?
0-16 means I only need 4 bits, so I should be able to store 2 different numbers in a single byte right?
The following code writes 1 number to 1 byte:
std::ofstream file;
file.open("test.bin", std::ios::binary|std::ios::out);
char oneByteNum = (char)fourByteNum; // Converting from some 4 byte integer to a 1 byte char
file.write(&oneByteNum ,sizeof(char));
Using bitshifts, how can I achieve 2 numbers in 1 byte? I imagine reading the number out of the byte would be a similar, inverse 2 step process too?
解决方案
char oneByteWithTwoNums = (oneByteNum1 << 4) + (oneByteNum2 & 0x0f);
这篇关于写入4位用的ofstream二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文