我们在工作中,有时候会需要将字符串转化为16进制字符串给用户,因为ASCII中有些字符,当我们使用printf("%s",p_ch);输出时会杂乱无章,如果采用16进制,会好很多。
因此编写程序,代码如下:
#include <stdio.h> #include <string.h> int strToHex(char *ch, char *hex); int hexToStr(char *hex, char *ch); int hexCharToValue(const char ch); char valueToHexCh(const int value); int main(int argc, char *argv[]) { char ch[1024]; char hex[1024]; char result[1024]; char *p_ch = ch; char *p_hex = hex; char *p_result = result; printf("please input the string:"); scanf("%s",p_ch); strToHex(p_ch,p_hex); printf("the hex is:%s ",p_hex); hexToStr(p_hex, p_result); printf("the string is:%s ", p_result); return 0; } int strToHex(char *ch, char *hex) { int high,low; int tmp = 0; if(ch == NULL || hex == NULL){ return -1; } if(strlen(ch) == 0){ return -2; } while(*ch){ tmp = (int)*ch; high = tmp >> 4; low = tmp & 15; *hex++ = valueToHexCh(high); //先写高字节 *hex++ = valueToHexCh(low); //其次写低字节 ch++; } *hex = '