用C语言演示如何执行下列类型转换:
1,获取字符串中每个字符的十六进制值。 2,获取与十六进制字符串中的每个值对应的字符。 3,将十六进制string转换为整型。 4,将十六进制string转换为浮点型。 5,将字节数组转换为十六进制string。
示例一 输出 string 中的每个字符的十六进制值。
char str[]="Hello World!";
int i;
printf("Hello World!\n");
for(i=0;i
{
printf("%02u: %c 字符十六进制 = %x \r\n",i,str[i],str[i]);
}
输出结果
示例二 分析十六进制值的 string 并输出对应于每个十六进制值的字符
char hexValues[] = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
int i;
char var,temp,count;
char strTb[20],strNum;
strNum = 0;
count = 0;
for(i=0;i
{
temp = hexValues[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp
{
temp = temp - '0';
}else if((temp >= 'A') && (temp
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
var
var +=temp;
count++;
if(count >= 2)
{
printf("hexadecimal value = %x, int value = %3u, char value = %c\r\n",var,var,var);
strTb[strNum] = var;
strNum ++;
var = 0;
count = 0;
}
}
输出结果
示例三 演示了将十六进制 string 转换为整数
char hexString[] = "8E2";
char temp;
unsigned int i,IntVar=0;
IntVar=0;
for(i=0;i
{
temp = hexString[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp
{
temp = temp - '0';
}else if((temp >= 'A') && (temp
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
IntVar
IntVar +=temp;
}
printf("字符串hexString整形值为:%lu\r\n",IntVar);
输出结果
示例四 演示如何将十六进制 string 转换为浮点型。
const char floatString[] = "4348016f";
int i,strNum,count;
char var,temp;
typedef union
{
float floatVar;
unsigned char byte[4];
}ParType_un;
ParType_un outPar;
strNum = 0;
count = 0;
for(i=0;i
{
temp = floatString[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp
{
temp = temp - '0';
}else if((temp >= 'A') && (temp
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
var
var +=temp;
count++;
if(count >= 2)
{
outPar.byte[3-strNum] = var;
strNum ++;
var = 0;
count = 0;
}
}
printf("字符串floatString浮点值为:%f\r\n",outPar.floatVar);
输出结果
示例五 下面的示例演示如何将字节数组转换为十六进制字符串。
const unsigned char vals[6] = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };
int i;
char temp;
for(i=0;i
{
printf("%02x",vals[i]);
}
printf("\r\n");
输出结果
领取专属 10元无门槛券
私享最新 技术干货