Reputation: 159
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?
Upvotes: 1
Views: 2587
Reputation: 1287
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
.
Upvotes: 2
Reputation: 21607
unsigned char c1 = static_cast<unsigned char>(example & 0xFF) ;
unsigned char c2 = static_cast<unsigned char>((example >> 8) & 0xFF) ;
unsigned char c3 = static_cast<unsigned char>((example >> 16) & 0xFF) ;
unsigned char c4 = static_cast<unsigned char>((example >> 24) & 0xFF) ;
Upvotes: 1
Reputation: 882
union split_union
{
int as_int;
char as_char[4];
}
// either initialize like this...
split_union example{0x38600000};
// or assign like this...
split_union ex;
ex.as_int = 0x38600000;
//example.as_char[0] = 0x00;
//example.as_char[1] = 0x00;
//example.as_char[2] = 0x60;
//example.as_char[3] = 0x38;
// correct order for Visual Studio on x86.
Upvotes: 1