Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中字符从大端到小端的转换_C_Char_Endianness - Fatal编程技术网

C语言中字符从大端到小端的转换

C语言中字符从大端到小端的转换,c,char,endianness,C,Char,Endianness,我正在尝试将char变量从big-endian转换为little-endian 这里就是: char name[12]; 我知道如何在大尾端和小尾端之间转换int,但是字符把我搞糊涂了 我知道我必须先把它转换成整数形式,我有 对于转换int,我使用的是: (item.age >> 24) | ((item.age >> 8) & 0x0000ff00) | ((item.age << 8) & 0x00ff0000) | (item.age

我正在尝试将char变量从big-endian转换为little-endian

这里就是:

char name[12];
我知道如何在大尾端和小尾端之间转换int,但是字符把我搞糊涂了

我知道我必须先把它转换成整数形式,我有

对于转换int,我使用的是:

(item.age >> 24) | ((item.age >> 8) & 0x0000ff00) | ((item.age << 8) & 0x00ff0000) | (item.age << 24);

(item.age>>24)|((item.age>>8)&0x0000ff00)|((item.age尾数只影响字节顺序。由于
char
正好是一个字节,因此在所有尾数格式上都是相同的

请注意:您可能需要在libc中查找endianess转换函数:

htonl, htons
ntohl, ntohs
当涉及到单字节类型时,字节顺序(又称Endian ness)没有任何意义

虽然
char name[12]
由12个字节组成,但其类型的大小是单个字节

所以你不需要用它做任何事

顺便说一句,
int
的大小不一定在所有编译器上都是4字节,因此您可能希望使用更通用的转换方法(对于任何类型):

char*p=(char*)&item;

对于(int i=0;iSo我不需要对它做任何事情?@PM No:)不要担心
char
@PM:宽字符的情况会有所不同,
wchar\u t
。@SergeyL.谢谢!这让事情变得简单多了!我从来没有见过大端系统。我想所有有英特尔处理器的机器都是小端。我知道,但我已经知道我要处理的int的大小,谢谢你就像老工程师曾经称赞的那样,“我不得不收回我说过的关于你的一半坏话。”;)@P M这些帖子和答案不仅仅是给你的,也是给其他人的参考。即使在这篇帖子的例子中,
int
大小可能不是一个问题,变量
int
大小也可能适用于其他人。@ajay
char
是每个C标准的1字节。但是一个C字节不能保证是8位。a
char和字节必须至少为8位。请参阅
CHAR\u BIT
。当然,大多数系统使用8位字节。POSIX要求CHAR\u BIT==8。
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;
}