简体   繁体   English

使用ofstream将4位写入二进制文件

[英]Writing 4 bits to a binary file with ofstream

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之间的无符号整数,并且想将其写入二进制文件而不向其写入整个字节,那么如何将其移位一位来实现呢?

0-16 means I only need 4 bits, so I should be able to store 2 different numbers in a single byte right? 0-16表示我只需要4位,因此我应该能够在一个字节中存储2个不同的数字,对吗?

The following code writes 1 number to 1 byte: 以下代码将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));

Using bitshifts, how can I achieve 2 numbers in 1 byte? 使用移位,如何在1个字节中获得2个数字? I imagine reading the number out of the byte would be a similar, inverse 2 step process too? 我想从字节中读取数字也将是一个类似的逆2步过程吗?

char oneByteWithTwoNums = (oneByteNum1 << 4) + (oneByteNum2 & 0x0f);

Try this: 尝试这个:

  compacted = first_number * 0x10 + second-number;

To expand: 扩张:

  second_number = compacted & 0x0F;
  first_number = compacted >> 4;

I wrote up a quick example: 我写了一个简单的例子:

#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;
}

You'll probably want to add checks in your pack/unpack methods to ensure someone doesn't try passing in a value other than [0-15]. 您可能希望在您的打包方法中添加检查,以确保某人不会尝试传递[0-15]以外的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM