首页 > 编程知识 正文

ascii码转换成十进制,字符串转16进制函数

时间:2023-05-06 07:23:30 阅读:169736 作者:2606

C编程可能需要将字符串转换为相应的十六进制ASCII代码字符串并将其显示。 这里是我参考网上代码编写的转换程序:

这个程序分为两个部分。

一、将字符串转换为对应的十六进制数值

intstr2hex(char*str,char *hex ) {int high=0; int low=0; int temp=0; 空值==str||空值==hex )打印(' thestrorhexiswrongn ' ); 返回- 1; }if(0==strlen(str ) ) printf ) ' theinputstriswrongn ' ); 返回- 2; (while ) str ) temp=(int ) ) str ); high=temp4; low=temp 15; *hex=value2hex(high ); hex; *hex=value2hex(low; hex; str; }*hex=' '; 返回0; (二)上述代码用于将数值型数值转换为字符型数字。 那个代码如下所示。

charvalue2hex(constintvalue ) {char Hex=NULL; if(value=0value=9) hex=(char ) (value '0' ); }else{if(value9value16 ) hex=(char ) ) value-10 'A ' ); } else { printf (theinputvalueisoutofrange (n ); }}return Hex; }

完整的代码如下所示。

# include stdio.h

# include string.h

charvalue2hex(constintvalue ) )。

{

char Hex=NULL;

if(value=0value=9) {

hex=(char ) ) value '0);

}

else{

if (值9值16 ) {

hex=(char ) ) value-10 'A ) a );

}

else{

printf (theinputvalueisoutofrange (n );

}

}

返回hex;

}

intstr2hex(char*str,char *hex ) ) )。

{

int high=0;

int low=0;

int temp=0;

if (空值==str||空值==hex ) {

打印(thestrorhexiswrong (n ) );

返回- 1;

}

if(0==strlen(str ) ) }

打印(theinputstriswrong (n ) );

返回- 2;

}

wile(*str ) {

temp=(int ) ) str;

high=temp4;

low=temp 15;

*hex=value2hex(high );

hex;

*hex=value2hex(low;

hex;

str;

}

*hex=' ';

返回0;

}

int main () )

{

char * a='OK ';

char b[512];

str2hex(a,b );

printf(%s(n ),b );

返回0;

}

当然,也有一种简单粗暴的方法,即在sprintf中进行转换,但有一个限制,就是只能一次转换一个字符。

#include stdio.h

#include stdlib.h

int main () )

{

char a[512];

char b='K ';

sprintf(a,' %x ',b );

printf(%s(n ),a );

返回0;

}

PS:还可以通过itoa在第2步中将整数值转换为字符型数值。

上述转换程序有几个缺点,它们不能用于转换非字符串数据,因此要编写另一个程序进行转换。 如下所示。

satic char value2hex (const intvalue ) {char hex=NULL; if(value=0value=9) hex=(char ) (value '0' ); }else{if(value9value16 ) hex=(char ) ) value-10 'A ' ); } else { nbw fprintf (' theinputvalueinthefunctionvalue2hexisoutofrangen ' ); usleep(1000*1000 ); }}return hex; }staticintstr2hex(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; 空值==str||空值==hex ) nbw fprintf (' thestrorhexiswrongn ' ); usleep(1000*1000 ); 结果=1; }if(0==temp_len ) nbw fprintf (the str2hexneedthelengthofthestrn ' ); usleep(1000*1000 ); 返回- 2; }while(temp_Len---- ) temp=(int ) ) str ); high=temp4; low=temp 15; *hex=value2hex(high ); hex; *hex=value2hex(low; hex; str; }*hex=' '; 返回0; }

该程序与以前的程序的最大区别在于,它以输入的长度而不是字符的NULL标志结束转换,从而提高了使用范围。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。