在C的编程中, 有时需要将字符串转换为对应的16进制的ASCII码字符串并显示出来。这里是我参考网上代码写的转换程序:
该程序分为两个部分:
一、先将字符串转换为对应的16进制的数值
int Str2Hex(char *str,char *hex)
{
int high = 0;
int low = 0;
int temp = 0;
if (NULL==str || NULL==hex){
printf("the str or hex is wrong\n");
return -1;
}
if (0==strlen(str)){
printf("the input str is wrong\n");
return -2;
}
while(*str){
temp = (int)(*str);
high = temp>>4;
low = temp & 15;
*hex = Value2Hex(high);
hex++;
*hex = Value2Hex(low);
hex++;
str++;
}
*hex = '\0';
return 0;
}
char Value2Hex(const int value)
{
char Hex = NULL;
if (value>=0 && value<=9){
Hex = (char)(value+'0');
}
else{
if (value>9 && value<16){
Hex = (char)(value-10+'A');
}
else{
printf("the input value is out of range\n");
}
}
return Hex;
}
# include <stdio.h>
# include <string.h>
char Value2Hex(const int value)
{
char Hex = NULL;
if (value>=0 && value<=9){
Hex = (char)(value+'0');
}
else{
if (value>9 && value<16){
Hex = (char)(value-10+'A');
}
else{
printf("the input value is out of range\n");
}
}
return Hex;
}
int Str2Hex(char *str,char *hex)
{
int high = 0;
int low = 0;
int temp = 0;
if (NULL==str || NULL==hex){
printf("the str or hex is wrong\n");
return -1;
}
if (0==strlen(str)){
printf("the input str is wrong\n");
return -2;
}
while(*str){
temp = (int)(*str);
high = temp>>4;
low = temp & 15;
*hex = Value2Hex(high);
hex++;
*hex = Value2Hex(low);
hex++;
str++;
}
*hex = '\0';
return 0;
}
int main()
{
char * a = "OK";
char b[512];
Str2Hex(a,b);
printf("%s\n",b);
return 0;
}
当然,还有一种简单粗暴的方法,便是通过sprintf来进行转换,但其有一个限制便是只能一个一个字符地进行转换。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[512];
char b= 'K';
sprintf(a,"%x",b);
printf("%s\n",a);
return 0;
}
PS:在第二步中,将整型数值转换为字符型数值也可通过itoa实现。
上述的转换程序会存在着一些的缺陷,其无法用于将非字符串的数据进行转换,故另一个程序编写来进行转换,其如下:
static char Value2Hex(const int value)
{
char hex = NULL;
if(value>=0 && value<=9){
hex = (char)(value+'0');
}
else{
if(value>9 && value<16){
hex = (char)(value-10+'A');
}
else {
NbwfPrintf("the input value in the function Value2Hex is out of range\n");
usleep(1000*1000);
}
}
return hex;
}
static int Str2Hex(char *str, char *hex, char Str_Len)
{
int high = 0;
int low = 0;
int result = 0;
int temp_len = (int)Str_Len;
int temp =0;
if(NULL==str || NULL==hex){
NbwfPrintf("the str or hex is wrong\n");
usleep(1000*1000);
result = 1;
}
if(0==temp_len){
NbwfPrintf("the Str2Hex need the length of the str\n");
usleep(1000*1000);
return -2;
}
while(temp_len--){
temp = (int)(*str);
high = temp>>4;
low = temp & 15;
*hex = Value2Hex(high);
hex++;
*hex = Value2Hex(low);
hex++;
str++;
}
*hex = '\0';
return 0;
}