// get bits zero to 7
int bitsZeroToSeven = inputInt & (0x000000FF);
// get bits 8to 15
int bitsEightToFifteen = inputInt & (0x0000FF00);
// Now shift them along to occupy the lowest 8 bits
bitsEightToFifteen = bitsEightToFifteen >> 8;
Hang on. How could I use this code in a function? This is what my function would look like: int DecompileInt(int input, int id);
In this function, 'input' is the integer that will be decompiled, and 'id' is which integer to get (like the first one or the second etc). How can I implement Moschops's code for this?
There are 8 bits for each byte. So you can multiply the ID number by 8 and that is how many bits you need to shift. After shifting you can mask out the low 8 bits.
int decompile(int input, int id)
{
union
{
int a;
unsignedchar num[4];
};
a=in;
returnint(num[id-1]);
}
int compile(int a, int b, int c, int d)
{
union
{
int a;
unsignedchar num[4];
};
num[0]=a;
num[1]=b;
num[2]=c;
num[3]=d;
return a;
}
#include <iostream>
usingnamespace std;
int decompile(int input, int id)
{
union
{
int a;
unsignedchar num[4];
};
a=input;
returnint(num[id-1]); // This takes care of counting from zero
}
int main()
{
int z = 0x09080706;
cout << decompile(z,4) << " "
<< decompile(z,3) << " "
<< decompile(z,2) << " "
<< decompile(z,1);
}
Technically, this is undefined behavior. You can't write to one member of a union and read from another. That said, I don't know of any compilers which don't handle this in reasonable way.
@cire: it isn't undifened behaviour at all! "union" means that all of the elements in it occupy the same memory! band since an int is 4 times bigger than a char array of 4, the behaviour is complety defined, as long as you initiate at least one member.
$9.5 "In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time."