字符串和16进制字符串的相互转化
我们在工作中,有时候会需要将字符串转化为16进制字符串给用户,因为ASCII中有些字符,
当我们使用printf("%s",p_ch);输出时会杂乱无章,如果采用16进制,会好很多。
因此编写程序,代码如下:
$ gcc conver.c
c$ ./a.out
please input the string:!@#$%^&*()_+~`1234567890-=
the hex is:21402324255E262A28295F2B7E60313233343536373839302D3D
the string is:!@#$%^&*()_+~`1234567890-=
经测试,本代码如果输入中含有空格,则空格以后的字符串无法进行转化
测试的环境:
编译器: gcc 4.4.3
操作系统:ubuntu 10.04.4
内核版本:2.6.32-40-generic
当我们使用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 = " ";
-
return 0;
-
}
-
-
int hexToStr(char *hex, char *ch)
-
{
-
int high,low;
-
int tmp = 0;
-
if(hex == NULL || ch == NULL){
-
return -1;
-
}
-
-
if(strlen(hex) %2 == 1){
-
return -2;
-
}
-
-
while(*hex){
-
high = hexCharToValue(*hex);
-
if(high < 0){
-
*ch = " ";
-
return -3;
-
}
-
hex++; //指针移动到下一个字符上
-
low = hexCharToValue(*hex);
-
if(low < 0){
-
*ch = " ";
-
return -3;
-
}
-
tmp = (high << 4) + low;
-
*ch++ = (char)tmp;
-
hex++;
-
}
-
*ch = " ";
-
return 0;
-
}
-
-
int hexCharToValue(const char ch){
-
int result = 0;
-
//获取16进制的高字节位数据
-
if(ch >= "0" && ch <= "9"){
-
result = (int)(ch - "0");
-
}
-
else if(ch >= "a" && ch <= "z"){
-
result = (int)(ch - "a") + 10;
-
}
-
else if(ch >= "A" && ch <= "Z"){
-
result = (int)(ch - "A") + 10;
-
}
-
else{
-
result = -1;
-
}
-
return result;
-
}
-
-
char valueToHexCh(const int value)
-
{
-
char result = " ";
-
if(value >= 0 && value <= 9){
-
result = (char)(value + 48); //48为ascii编码的‘0’字符编码值
-
}
-
else if(value >= 10 && value <= 15){
-
result = (char)(value - 10 + 65); //减去10则找出其在16进制的偏移量,65为ascii的"A"的字符编码值
-
}
-
else{
-
;
-
}
-
-
return result;
- }
$ gcc conver.c
c$ ./a.out
please input the string:!@#$%^&*()_+~`1234567890-=
the hex is:21402324255E262A28295F2B7E60313233343536373839302D3D
the string is:!@#$%^&*()_+~`1234567890-=
经测试,本代码如果输入中含有空格,则空格以后的字符串无法进行转化
测试的环境:
编译器: gcc 4.4.3
操作系统:ubuntu 10.04.4
内核版本:2.6.32-40-generic
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: C语言中字符数组的初始化与赋值
- 下一篇: Web提速:避免php session拖慢运行速度