在C中将char从big endian转换为little endian
我正在尝试将char变量从big endian转换为little endian。
这正是:
char name[12];
我知道如何在大端和小端之间转换一个int,但是char会搞砸我。
我知道我必须首先将它转换为整数forms,我有。
为了转换int,这是我使用的:
(item.age >> 24) | ((item.age >> 8) & 0x0000ff00) | ((item.age << 8) & 0x00ff0000) | (item.age << 24);
为了转换char,如果可能的话,我想以同样的方式做到这一点,因为这是我理解的唯一方法。
Endianess仅影响字节顺序。 由于char
恰好是一个字节,因此在所有endianess格式上都是相同的。
并且作为注释:您可能想要在libc中查找endianess转换函数:
htonl, htons ntohl, ntohs
字节顺序(又名Endian-ness)在单字节类型方面没有任何意义。
虽然char name[12]
由12个字节组成,但其类型的大小是单个字节。
所以你不需要做任何事情……
顺便说一句, int
的大小在所有编译器上不一定是4个字节,所以你可能想要使用更通用的转换方法(对于任何类型):
char* p = (char*)&item; for (int i=0; i