Search code examples
c++binaryintmemcpy

Writing uint32_ts and uint_8ts to file as chars & then converting them back into uint32_ts and uint_8ts


I'm writing ints to a file like this:

for (int i = 0; i < 4; i++) {
    writeInt8ToFile(126, ofst);
    writeInt32ToFile(12500, ofst);
    writeInt8ToFile(139, ofst);
}

(Relevant functions):

void writeInt32ToFile(std::uint32_t i, std::fstream &fstr)
{
    fstr.write(reinterpret_cast<char *>(&i), sizeof(std::uint32_t));
}

void writeInt8ToFile(std::uint8_t i, std::fstream &fstr)
{
    fstr.write(reinterpret_cast<char *>(&i), sizeof(std::uint8_t));
}

Then, I would also like to be able to convert these chars back to integers.

I've already tried this:

(First, putting bytes to vector)

std::vector<char> infs_bytes(
        (std::istreambuf_iterator<char>(infs)),
        (std::istreambuf_iterator<char>()));

(Then, convert them back to int like this):

// Iterate through all bytes
for (int i = 0; i < btVec.size() / MAP_BYTE_SIZE; i++) {
    // Integers
    std::uint8_t i1;
    std::uint32_t i2;
    std::uint8_t i3;

    char buf[] = {btVec[i+1], btVec[i+2], btVec[i+3], btVec[i+4]}; // Middle 4 bytes

    // memcpy all bytes to their corresponding integer types
    std::memcpy(&i1, &btVec[i], 1); // First byte
    std::memcpy(&i2, buf, 4);
    std::memcpy(&i3, &btVec[i+5], 1); // Last byte

    std::cout << (int)i1 << std::endl;
    std::cout << i2 << std::endl;
    std::cout << (int)i3 << std::endl;
}

But, when I try to output to stdout as seen in the last snippet, this is what gets outputted:

126
139
212
126
48
212
0
48

Obviously, that's not what I wrote to the file. The expected output is

126
12500
139
126
12500
139
126
12500
139
126
12500
139


Solution

  • Your loop

    for (int i = 0; i < btVec.size() / MAP_BYTE_SIZE; i++) {
    

    is wrong. You have to move the starting position of each block MAP_BYTE_SIZE elements, not 1.

    Try

    for (int j = 0; j < btVec.size() / MAP_BYTE_SIZE; j++) {
        int i = j * MAP_BYTE_SIZE;