使用联合体将长整型数据的高字节和低字节拆分并输出结果
#include <iostream>
union MyUnion
{
long _long;
char _ch[4];
};
int main()
{
MyUnion unio;
unio._long = 2147483646;
for (int i = 0; i < 4; i++)
{
printf("%d\n", unio._ch[i]);
}
while (true)
{
}
return 0;
}
这是把一个long型用联合体转为char型输出,望采纳!
#include <stdio.h>
typedef union
{
long num;
struct
{
int low;
int high;
};
}NUM;
int check_sys()
{
union _test
{
int a;
char b;
} test;
test.a = 1;
if (test.b == 1)
{
printf("Little_endian!\n");
return 0;
}
else
{
printf("Big_endian!\n");
return 1;
}
}
int main()
{
check_sys();
printf("long size:%lu int size:%lu\n", sizeof(long), sizeof(int));
NUM test;
test.num = 0x2222222211111111;
printf("high addr:0x%X %X\n", (int)&test.high, test.high);
printf("low addr:0x%X %X\n", (int)&test.low, test.low);
}
编译输出:
root# gcc 1.c
root# ./a.out
Little_endian!
long size:8 int size:4
high addr:0x72B612F4 22222222
low addr:0x72B612F0 11111111