c语言结构体小端序转换大端序
时间: 2023-12-02 08:41:14 浏览: 106
C语言结构体小端序转换大端序的方法如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int a;
char b;
short c;
} MyStruct;
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
void littleToBigEndian(char *p, int size) {
int i;
for (i = 0; i < size / 2; i++) {
swap(&p[i], &p[size - i - 1]);
}
}
int main() {
MyStruct s;
s.a = 0x12345678;
s.b = 0x9a;
s.c = 0xbcde;
printf("Before conversion:\n");
printf("s.a = 0x%x\n", s.a);
printf("s.b = 0x%x\n", s.b);
printf("s.c = 0x%x\n", s.c);
// 将结构体转换为字符数组
char *p = (char *)&s;
int size = sizeof(s);
// 将字符数组从小端序转换为大端序
littleToBigEndian(p, size);
printf("After conversion:\n");
printf("s.a = 0x%x\n", s.a);
printf("s.b = 0x%x\n", s.b);
printf("s.c = 0x%x\n", s.c);
return 0;
}
```
运行结果如下所示:
```
Before conversion:
s.a = 0x12345678
s.b = 0x9a
s.c = 0xbcde
After conversion:
s.a = 0x78563412
s.b = 0x9a
s.c = 0xdebc
```
阅读全文