I'm trying to convert a char variable from big endian to little endian.
Here it is exactly:
char name[12];
I know how to convert an int between big and little endian, but the char is messing me up.
I know I have to convert it to integer form first, which I have.
For converting an int this is what I used:
(item.age >> 24) | ((item.age >> 8) & 0x0000ff00) | ((item.age << 8) & 0x00ff0000) | (item.age << 24);
For converting the char, I'd like to do it in the same way, if possible, just because this is the only way I understand how to.
Endianess only affects byte order. Since char
is exactly one byte it is the same on all endianess formats.
And as a note: you may want to look up the endianess conversion functions in libc:
htonl, htons
ntohl, ntohs
Byte-order (a.k.a. Endian-ness) has no meaning when it comes to single-byte types.
Although char name[12]
consists of 12 bytes, the size of its type is a single byte.
So you need not do anything with it...
BTW, the size of int
is not necessarily 4 bytes on all compilers, so you might want to use a more generic conversion method (for any type):
char* p = (char*)&item;
for (int i=0; i<sizeof(item)/2; i++)
{
char temp = p[i];
p[i] = p[sizeof(item)-1-i];
p[sizeof(item)-1-i] = temp;
}