Search code examples
c++bytearraysendianness

why are the bytes in byte array reversed in C++


the code i am trying to understand overwrites a section of a game process memory (window.h, WriteProcessMemory) in order to modify a parameter in the game (for example, strength). the values would most likely be integers

the code attempts replacement with this function

WriteProcessMemory( GameHandle, (BYTE*)StrengthMemoryAddress, &StrengthValue, sizeof(StrengthValue), NULL);

where StrengthMemoryAddress is a pre-calculated dynamic address and StrengthValue is the following:

byte StrengthValue[] = { 0x39, 0x5, 0x0, 0x0 };

it replaces strength with 1337

my question is basically how the byte array works in this function. from google i know that the hex value of 1337 is 0x539.

how come you have to reverse it in the byte array? i see that he first puts 0x39 then 0x5, which i concluded probably combines to 0x539 in some reverse order. also, why do you need the extra 0x0 at the end - can't you just leave it out?

thanks


Solution

  • from google i know that the hex value of 1337 is 0x539.

    Or it is 0x00000539 which is same but written as a 4 byte integer. Now if you write this integer in little endian way in memory you would have to store it in following order (Least significant byte - 0x39 - goes first):

    Memory Address   Values
    1000             0x39  
    1001             0x05
    1002             0x00
    1003             0x00
    

    So that has to do with endianness. You may want to read more on that topic.