neophoenix
neophoenix

Reputation: 66

C++ write nibbles in file

Good evening, I'm new to C++ and encountered a problem that I wasn't able to solve despite reading numerous pages here. I've got a file with hexvalues that need to be read and compressed, then written in a new file. An example sequence looks like this:

C9 CB FF 01 06 (each byte [8 bit] represent a number)

Compression starts with the first number, then only writing the difference to the next number (differences are a nibble [4 bit]). Example from C9 to CB: difference = 2. If the difference is greater than 7, thus can't be represented by a nibble, we use a 0x8 to mark a new start. 0xFF-0xCB > 7 so the sequence would look like this (entire compressed code):

C9 28 FF 15 (mixture of entire bytes (0xC9 and 0xFF) representing numbers and nibbles representing differences to the next number. Now to my problem. I'm using fstream and put to write bytes to a new file, nibbles are stored to combine with an other nibble to a byte which can be written to the file. However it only works with bytes smaller than 128 so I can't write values greater than 0x7F into a file. I prepared a file with notepad++ starting with the value 0xFF - reading that value works great but dest.put(source.get()); doesn't in that specific case. How can I work with (signed) nibbles [for negative differences] and binary presentations of numbers in C++? By the way using negative numbers in file.put() results in strange behavior as 2 bytes are written rather than one. Here's my code, I hope you understand my problem and I really appreciate your help

int lastValue = s.get();
d.put((char)lastValue);
char highNibble = 0;
bool nibbleSet = false;
int diff = 0;
for (int c = s.get(); c != -1; c = s.get()) {
    diff = (char)((unsigned char)c - (unsigned char)lastValue);
    if (abs(diff) > 7) {
        if (nibbleSet) {
            d.put(highNibble << 4 | 8);
            d.put((char)c);
            nibbleSet = false;
        }
        else {
            cout << (8 << 4 | (c & 0xF0) >> 4) << endl;
            d.put(8 << 4 | (c & 0xF0) >> 4);
            highNibble = c & 0x0F;
            nibbleSet = true;
        }
    }
    else {
        if (nibbleSet) {
            d.put(((char)highNibble << 4) & 0xF0 | ((char)diff) & 0x0F);
            nibbleSet = false;
        }
        else {
            highNibble = (char)diff;
            nibbleSet = true;
        }
    }
    lastValue = c;
}

Upvotes: 0

Views: 352

Answers (0)

Related Questions