My only guess is that it relates to the 'endianess' of the values, and that my function is printing them 'backwards'.
Yes, that's correct.
The machine you are using is 'little endian', which means that it stores numbers in memory in lowest to highest significant byte order.
If you want to extract bytes in the correct order regardless of 'endianness' then use shifting and masking.
Code:
unsigned int i = 0x01234567;
byte0 = (i >> 24) & 0xFF; // 0x01
byte1 = (i >> 16) & 0xFF; // 0x23
byte2 = (i >> 8) & 0xFF; // 0x45
byte3 = i & 0xFF; // 0x67
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
My compiler wouldn't even print anything via the printf. I don't think it is a good idea to mix printf and cout in the same program. I may not have included the correct headers or for some reason the output stream wasn't being flushed in the posted program. You could just do it with with std::cout.
Code:
int main ()
{
unsigned int MDBuffer [4] = {0x01234567, 0x89abcdef, 0xfedcba98, 0x76543210};
unsigned char * outChars = (unsigned char*) &MDBuffer;
// prints backwards
for(int i = 0; i<16; i++)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<short>(*(outChars+i));
}
std::cout << std::endl;
// prints forwards. This outputs the data in the way that you wanted it.
for(int i = 0; i<4; i++)
{
std::cout << std::hex << std::setfill('0') << std::setw(8) << MDBuffer[i];
}
std::cout << std::endl;
return 0;
}
// prints backwards
for(int i = 0; i<16; i++)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<short>(*(outChars+i));
}
Only for 'little endian' machines. For 'big endian' machines it will print forwards.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
It's probably not optimal, and wouldn't work on a big-endian machine... but since I'm only doing this as a programming exercise, it's probably good enough!
I think I understand the problem and some possible solutions now anyways, so thanks. All this code-portability stuff drives me mad!
Is there some reason you don't simply do
Code:
for (int i = 0; i < 4; ++i)
printf("%08x ", MDBuffer[i]);
1) I didn't think of it *facepalm*.
2) I wanted the output to be split up in groups of two to make it more readable anyways.
Last edited by Flembobs; January 30th, 2009 at 07:51 AM.
Bookmarks