Search code examples
c++memoryint32-bit

C++ Split Int Into 4 Parts (32 Bit Machine)


Alright so If I have an int like this (used to store a line of ASM)

int example = 0x38600000; //0x38600000 = li r3, 0 

How would I split this int into 4 seperate sections? I've come up with this

int example = 0x38600000;
char splitINT[4];
for(int i = 0; i < 4; i++)
{
    splitINT[i] = *(char*)(((int)&example + (0x01 * i)));
}
//splitINT[0] = 0x38;
//splitINT[1] = 0x60;
//splitINT[2] = 0x00;
//splitINT[3] = 0x00;

The above code actually works perfectly fine when reading memory from the process my executable is running within, but this does not work when trying to read the programs own memory from within itself like shown in the code example above.

So how else would I go about splitting an int into 4 separate parts?


Solution

  • Your code is really confusing since I am not sure why it works at all given the cast to int in the statement. You can read each individual byte of the 32-bit int by casting it to a char *, where a char is the size of one byte on your machine.

    int example = 0x38600000;
    char *bytepointer = reinterpret_cast<char*>(&example);
    for(int i = 0; i < 4; i++)
    {
        std::cout << static_cast<int>(bytepointer[i]) << " ";
    }
    
    std::cout << std::endl;
    

    You can also use bytepointer to modify the memory contents of the int byte by byte.

    Additionall, you should also look up the role of endianness in determining the memory layout of integers. A machine can choose to use a big- or small-endian layout, and this will change the order in which the bytes are printed and how you can modify the int.