Home > Mobile >  recombining 32 bit integer from 8 bit components
recombining 32 bit integer from 8 bit components

Time:01-07

I have read 4 chars from a file. For instance 11110000 00001111 11000011 00111100 read in that order. i need to combine these from individual chars to form a continuous single uint32_t 11110000000011111100001100111100. Here is a solution i decided that seemed to work until it didn't.

//#include <fstream>

#include <cstdint>

#include <iostream>

//std::fstream File("example", std::ios::binary | std::ios::out | std::ios::in);

char FileDataExpectedResult[4] = {0x00, 0x00, 0x00, 0x0D};
char FileDataUnexpectedResult[4] = {0x00, 0x00, 0x03, 0x64};

uint32_t Reasemble(char* FileDataArray) 
{
    uint32_t Result=0x0;
    
    char ComponentByte;

    for (int ByteIterator=0; ByteIterator<4; ByteIterator   ) 
    {
        //File.read(&ComponentByte, 1);
        ComponentByte = FileDataArray[ByteIterator];

        uint32_t ExtendedComponentByte = 0x0000 | ComponentByte;

        Result = Result | (ExtendedComponentByte << ((32/(ByteIterator 1)-8)));
    }

    return Result;
}

int main() {
    
    uint32_t Expected = Reasemble(FileDataExpectedResult);
    uint32_t Unexpected = Reasemble(FileDataUnexpectedResult);

    std::cout << "hopefully 13: " << (int)Expected << "\n";
    std::cout << "hopefully 868: " << (int)Unexpected << "\n";

    return 1;
}

this code is recreated in a simpler environment stripped of context. When this code reads 0x0000000D from a file it correctly converts it to 13. However, 0x00000364 returns 108 instead of the expected 868. The idea was is reading byte by byte then putting it in a 32bit number and shifting it depending on what byte it should be in the 32bit number, then or'ing each one with a singular 32 bit number to combine them.

CodePudding user response:

The error is in ((32/(ByteIterator 1)-8)) -- I'm sure that's not what you want. I think (24 - (ByteIterator*8)) is what you were aiming for.

However, there are library functions for this sort of thing (tadman suggested ntohl).

  • Related