Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting wrong hex value from read function

Function gets valid data by 1 step, but when go to 2 step gets wrong hex data, what i`m doing wrong?

stringstream getHexFromBuffer(char* buffer,short startFrom = 0, short to = 4)
{
    int len = strlen(buffer);
    stringstream hexValue;
    for (size_t i = startFrom; i < to; i++) {
        hexValue << hex << (int)buffer[i];
    }
    return hexValue;
}

bool big::openFile(std::string fName){
    this->fileName = fName;
    
    ifstream file(fName.c_str(), ios::binary | ios::out | ios::ate);

    char* memblock;

    this->fileSize = file.tellg();

    memblock = new char[16];

    file.seekg(0, ios::beg);

    if (!file.is_open()) {
        file.close();
        throw new exception("Файл не может быть открыт!");
    }
    file.read(memblock, 16);
    string bigCheck = hexToASCII(getHexFromBuffer(memblock).str());

    if (strcmp(bigCheck.c_str(), "BIGF") != 0) {
        throw new exception("Не .BIG архив!");
    }
    this->fileType = bigCheck.c_str();

    string bigSize = getHexFromBuffer(memblock, 4, 8).str();
    //cout << getIntFromHexString(bigSize) << endl << this->fileSize ;

    file.close();
}

First valid attempt

Second not valid attempt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Must be d0998100, but get ffffffd0ffffff99ffffff810 instead

Full hex that i trying to get is 42 49 47 46 D0 99 81 00, maybe it helps

>Solution :

d0 is a negative 8 bit value in signed char. This is exact the same negative value ffffffd0 in int. For getting "d0" in output, cast the signed char to another unsigned type of the same size (1 byte) then cast the result to int:

hexValue << hex << (int)(unsigned char)buffer[i];
hexValue << hex << (int)(uint8_t)buffer[i];

The first cast keeps 8 bits in a unsigned type, a positive number, the second cast makes a positive int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading