如果我有一个介于0到16之间的无符号整数,并且我想将其写入二进制文件而不向其写入整个字节,那么如何移位来实现它?
0-16意味着我只需要4位,所以我应该可以在一个字节中存储2个不同的数字吗?
以下代码将1个数字写入1个字节:
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));
使用位移,如何在1字节中实现2个数字? 我想从字节中读取数字也是一个类似的反向2步过程吗?
答案 0 :(得分:3)
char oneByteWithTwoNums = (oneByteNum1 << 4) + (oneByteNum2 & 0x0f);
答案 1 :(得分:1)
试试这个:
compacted = first_number * 0x10 + second-number;
扩展:
second_number = compacted & 0x0F;
first_number = compacted >> 4;
答案 2 :(得分:1)
我写了一个简单的例子:
#include <iostream>
typedef unsigned char byte;
byte pack(unsigned int num1, unsigned int num2) {
// Our byte has the form 0b00000000
// We want the first four bits to be filled with num1
byte packed = num1 << 4;
// We want the last four bits to be filled with num2
// but, we don't want to overwrite the top four bits, so
// we mask it with 0x0F (0b0001111)
packed |= num2 & 0x0F;
return packed;
}
void unpack(byte b, unsigned int& num1, unsigned int& num2) {
// Extract the first four bits of our byte
num1 = b >> 4;
// Mask off the first four bits of our byte to get only
// the last four bits
num2 = b & 0x0F;
}
int main() {
unsigned int num1 = 5; // As an example
unsigned int num2 = 15; // As an example
byte b = pack(num1, num2);
unsigned int num3;
unsigned int num4;
unpack(b, num3, num4);
std::cout << num3 << std::endl;
std::cout << num4 << std::endl;
return 0;
}
您可能希望在pack / unpack方法中添加检查,以确保有人不会尝试传递[0-15]以外的值。