Convert char from big endian to little endian in C

和自甴很熟 提交于 2019-12-11 01:59:34

问题


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.


回答1:


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



回答2:


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;
}


来源:https://stackoverflow.com/questions/21761952/convert-char-from-big-endian-to-little-endian-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!