dimanche 22 novembre 2020

C++ Write char to file by nibbles

I have some problem with a writing to file in C++. I need to write a number to the file. The result must look like this. It's BCD code. But I don't know how to write that 'C'.

struct BCD {
char a: 4, b: 4; 
};

.
.
.
ofstream os("output.txt", ofstream::binary);
int number = 2;
bitset<8> bits;
char c;
if (number < 0) c = '0xD';
else c = '0xC';
string str = to_string(number) + c;
if (str.length() % 2) str.insert(0, 1, '0');
for (int i = 0; i < str.length(); i++) {
    BCD bcd;
    bcd.a = str[i];
    bcd.b = str[++i];
    auto bcda_bits = bitset<4>(bcd.a);
    auto bcdb_bits = bitset<4>(bcd.b);
    for (int j = 0; j < 8; j++) {
        if (j < 4)
            bits[j] = bcdb_bits[j];
        else
            bits[j] = bcda_bits[j - 4];
    }
    os << static_cast<uint_fast8_t>(bits.to_ulong());
}

.
.
.

Aucun commentaire:

Enregistrer un commentaire