字串和16進位制字串的相互轉化
阿新 • • 發佈:2019-01-09
我們在工作中,有時候會需要將字串轉化為16進位制字串給使用者,因為ASCII中有些字元,
當我們使用printf("%s",p_ch);輸出時會雜亂無章,如果採用16進位制,會好很多。
因此編寫程式,程式碼如下:
$ gcc conver.c
c$ ./a.out
please input the string:[email protected]#$%^&*()_+~`1234567890-=
the hex is:21402324255E262A28295F2B7E60313233343536373839302D3D
the string is:[email protected]#$%^&*()_+~`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 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\n",p_hex)
-
hexToStr(p_hex, p_result);
-
printf("the string is:%s\n", 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 >
-
low = tmp & 15;
-
*hex++ = valueToHexCh(high); //先寫高位元組
-
*hex++ = valueToHexCh(low); //其次寫低位元組
-
ch++;
-
}
-
*hex = '\0';
-
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 = '\0';
-
return -3;
-
}
-
hex++; //指標移動到下一個字元上
-
low = hexCharToValue(*hex);
-
if(low < 0){
-
*ch = '\0';
-
return -3;
-
}
-
tmp = (high << 4) + low;
-
*ch++ = (char)tmp;
-
hex++;
-
}
-
*ch = '\0';
-
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 = '\0';
-
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:[email protected]#$%^&*()_+~`1234567890-=
the hex is:21402324255E262A28295F2B7E60313233343536373839302D3D
the string is:[email protected]#$%^&*()_+~`1234567890-=
經測試,本程式碼如果輸入中含有空格,則空格以後的字串無法進行轉化
測試的環境:
編譯器: gcc 4.4.3
作業系統:ubuntu 10.04.4
核心版本:2.6.32-40-generic