嵌入式开发中,主机和从机通讯中,常常需要进行数据类型转换,下面就来写一个常用的int型转char类型数据的方法。
#include <stdio.h>
#include <string.h>
#define HIGH 1
#define LOW 0
#define NUM 4
void IntToStr(char *, int, int, int );
int main(void)
{
int value, i;
char str[NUM];
memset(str,0,NUM);
scanf("%d",&value);
IntToStr(str,value,NUM,LOW);
for(i=0;i<NUM;i++)
{
printf("%02X ",str[i]);
}
return 0;
}
/*目标地址,传入的数值,转换后的字节数,高或低字节在前*/
void IntToStr(char *dest, int value, int len, int higtlow)
{
char str_temp[4];
if(len == 2)
{
if(higtlow == HIGH)
{
str_temp[0] = (value>> 8)&0xff;
str_temp[1] = (value) &0xff;
}
else
{
str_temp[1] = (value>> 8)&0xff;
str_temp[0] = (value) &0xff;
}
*dest = str_temp[0];
*(dest+1) = str_temp[1];
}
else if(len == 4)
{
if(higtlow == HIGH)
{
str_temp[0] = (value>>24)&0xff;
str_temp[1] = (value>>16)&0xff;
str_temp[2] = (value>> 8)&0xff;
str_temp[3] = (value) &0xff;
}
else
{
str_temp[0] = (value>>24)&0xff;
str_temp[1] = (value>>16)&0xff;
str_temp[2] = (value>> 8)&0xff;
str_temp[3] = (value) &0xff;
}
*dest = str_temp[0];
*(dest+1) = str_temp[1];
*(dest+2) = str_temp[2];
*(dest+3) = str_temp[3];
}
}
/*运行*/
【12】
00 00 00 0C
/*运行*/
【127】
00 00 00 7F
看到这里我露出了开心的笑容,?
再试一个大点的数:
/*运行*/
【13456】
00 00 34 FFFFFF90
咦,为什么会这样,用计算器写10进制然后转16进制看一下。
除了多出来了FFFFFF,其他都是正常的,看看二进制位0011 0100 1001 0000,思考了一下,莫不是和符号有关,有符号数的最高位是符号位,1001 0000最高位为1,是负数,可能就是这样导致了异常输出。
多试了几次,发现只要每个字节的最高位是1,就会有FFFFFF出来。
更改一下代码:
unsigned char str[NUM];
貌似解决了~~~
试验一下:
/*运行*/
【13456】
00 00 34 90
OK
问题的细节不是很明白,我去找找看原因,找到了再更新一下。