Home > Back-end >  Getting wrong hex value from read function
Getting wrong hex value from read function

Time:02-19

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

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

CodePudding user response:

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 type cast keeps 8 bits in an unsigned type, a positive number, the second cast makes a positive int.

  • Related