概述
int is_little_endian(void)
{
unsigned short flag = 0x1234;
if(*(unsigned char *)&flag == 0x34)
return 1;
else
return 0;
}
int main(int argc, char* argv[])
{
union endian_un
{
short var;
char bits[sizeof(short)];
};
union endian_un flag;
flag.var = 0x0102;
if(sizeof(short) == 2)
{
if(flag.bits[0] == 1 && flag.bits[1] == 2)
printf("Judged by the first method,big_endiann");
else if(flag.bits[0] == 2 && flag.bits[1] == 1)
printf("Judged by the first method,little_endiann");
else
printf("Cann't judged the digtaln");
}
if(is_little_endian())
printf("Juged by the second method ,little_endiann");
else
printf("Juged by the second method,big_endiann");
return 0;
}
#include <stdio.h>
#include <stdio.h>
typedef unsigned int u32;
typedef unsigned short u16;
#if 0
//simple: not check varible types
#define BSWAP_16(x)
( (((x) & 0x00ff) << 8 ) |
(((x) & 0xff00) >> 8 )
)
//complex:check varible types
#else
#define BSWAP_16(x)
(u16) ( ((((u16)(x)) & 0x00ff) << 8 ) |
((((u16)(x)) & 0xff00) >> 8 )
)
#endif
#define BSWAP_32(x)
(u32) ( (( ((u32)(x)) & 0xff000000 ) >> 24) |
(( ((u32)(x)) & 0x00ff0000 ) >> 8 ) |
(( ((u32)(x)) & 0x0000ff00 ) << 8 ) |
(( ((u32)(x)) & 0x000000ff ) << 24)
)
u16 bswap16(u16 x)
{
return (x & 0x00ff) << 8 |
(x & 0xff00) >> 8
;
}
u32 bswap32(u32 x)
{
return ( x & 0xff000000 ) >>24 |
( x & 0x00ff0000 ) >>8 |
( x & 0x0000ff00 ) <<8 |
( x & 0x000000ff ) << 24
;
}
int main(void)
{
//u16 var_short = 0x123490;
//u32 var_int = 0x1234567890;
//关键是要能对错误进行处理,给一个0x123490 照样能得出 0x9034的值,而且, 占内存要小的
printf("macro conversion:%#xn",BSWAP_16(0x123490 ));//要能正确转换
printf("macro conversion:%#xn", BSWAP_32(0x1234567890)); //要能正确转换
printf("-----------------n");
printf("function conversion:%#xn",bswap16(0x123490));
printf("function conversion:%#xn", bswap32(0x1234567890));
return 0;
}
|
大小尾端数据间的相互转换
#include <stdio.h>
typedef unsigned int u32;
typedef unsigned short u16;
#define BSWAP_16(x)
(u16) ( ((((u16)(x) & 0x00ff)) << 8)
| (((u16)(x) & 0xff00) >> 8) )
u16 bswap_16(u16 x)
{
return ((x & 0x00ff) << 8) | ((x & 0xff00) >> 8);
}
u32 bswap_32(u32 x)
{
return ((x & 0x000000ff) << 24) |
((x & 0x0000ff00) << 8) |
((x & 0x00ff0000) >> 8) |
((x & 0xff000000) >> 24);
}
int main()
{
u16 num_16 = 0x1234;
u32 num_32 = 0x12345678;
printf("%xn", bswap_16(num_16));
printf("%xn", BSWAP_16(num_16));
printf("%xn", bswap_32(num_32));
return 0;
}
最后
以上就是幸福钢笔为你收集整理的嵌入式linux下关于大小尾端数据间的相互转换的全部内容,希望文章能够帮你解决嵌入式linux下关于大小尾端数据间的相互转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复