Original Post
I'm working on a project where I need to convert the bit pattern in an integer type to an array of chars (bytes), and vice versa. I'm wondering why this conversion always seems to "reverse" the order of the bytes. For example, when converting val = 0xAABBCCDD to an array of chars, the first element of the array will be 0xDD, the second 0xCC, etc., although I'm using a little endian system.
For me, the logical order would be 0xAA, 0xBB, 0xCC, 0xDD, because that is the order in which the bytes of val are stored in memory, isn't it?
Here is the code:
So I'm asking whether someone can explain to me why the order of bytes after conversion is 0xDDCCBBAA and not 0xAABBCCDD?
Btw, if you know a better way to convert between an integer type and a vector of chars, or notice any other stupidities in my code, please let me know.
For me, the logical order would be 0xAA, 0xBB, 0xCC, 0xDD, because that is the order in which the bytes of val are stored in memory, isn't it?
Here is the code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int one = 0x1;
cout << "The system is " << (((one << 1) == 0)? "big endian" : "little endian") << endl;
// This will output "little endian" on my system
vector<char> vec;
vec.push_back(0xAA);
vec.push_back(0xBB);
vec.push_back(0xCC);
vec.push_back(0xDD);
unsigned long* ul = reinterpret_cast<unsigned long*>(&vec[0]);
cout << hex << *ul << endl; // Why does this output 0xDDCCBBAA?
unsigned long n = 0xAABBCCDD;
vector<char> w;
w.assign( reinterpret_cast<char*>(&n), reinterpret_cast<char*>(&n) + sizeof(unsigned long) );
for(int i = 0; i < w.size(); i++) {
cout << hex << (int)(unsigned char)w; // this cast is because we want to print the bit pattern of w, not the character
}
cout << endl; // This will output in the "reverse" order as well: 0xDDCCBBAA0000
}
So I'm asking whether someone can explain to me why the order of bytes after conversion is 0xDDCCBBAA and not 0xAABBCCDD?
Btw, if you know a better way to convert between an integer type and a vector of chars, or notice any other stupidities in my code, please let me know.