用C语言演示如何执行下列任务:

1,获取字符串中每个字符的十六进制值。
2,获取与十六进制字符串中的每个值对应的字符。
3,将十六进制 string 转换为整型。
4,将十六进制 string 转换为浮点型。
5,将字节数组转换为十六进制 string。
头文件调用
示例一: 输出 string 中的每个字符的十六进制值。
char str[]="Hello World!";
int i;
printf("Hello World!n");
for(i=0;i<strlen(str);i++)
{
printf("%02u: %c 字符十六进制 = %x rn",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<strlen(hexValues);i++)
{
temp = hexValues[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp <= '9'))
{
temp = temp - '0';
}else if((temp >= 'A') && (temp <= 'F'))
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp <= 'f'))
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
var <<= 4;
var +=temp;
count++;
if(count >= 2)
{
printf("hexadecimal value = %x, int value = %3u, char value = %crn",var,var,var);
strTb[strNum] = var;
strNum ++;
var = 0;
count = 0;
}
}
strTb[strNum] = 0;
printf("获得字符串为:%s rn",strTb);
执行后结果
示例三: 演示了将十六进制 string 转换为整数
char hexString[] = "8E2";
char temp;
unsigned int i,IntVar=0;
IntVar=0;
for(i=0;i<strlen(hexString);i++)
{
temp = hexString[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp <= '9'))
{
temp = temp - '0';
}else if((temp >= 'A') && (temp <= 'F'))
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp <= 'f'))
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
IntVar <<= 4;
IntVar +=temp;
}
printf("字符串hexString整形值为:%lurn",IntVar);
执行后结果
示例四:演示如何将十六进制 string 转换为浮点型。
// 4 将十六进制 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<strlen(floatString);i++)
{
temp = floatString[i];
if(temp == ' ') continue;
if((temp >= '0') && (temp <= '9'))
{
temp = temp - '0';
}else if((temp >= 'A') && (temp <= 'F'))
{
temp = temp - 'A' + 10 ;
}else if((temp >= 'a') && (temp <= 'f'))
{
temp = temp - 'a' + 10 ;
}else
{
continue;
}
var <<= 4;
var +=temp;
count++;
if(count >= 2)
{
outPar.byte[3-strNum] = var;
strNum ++;
var = 0;
count = 0;
}
}
printf("字符串floatString浮点值为:%frn",outPar.floatVar);
执行后结果
示例五:下面的示例演示如何将字节数组转换为十六进制字符串。
const unsigned char vals[6] = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };
int i;
char temp;
for(i=0;i<sizeof(vals);i++)
{
printf("%02x",vals[i]);
}
printf("rn");
执行后结果


还没有评论,来说两句吧...