2011-03-23 284 views
10

我有一個十六進制字符串,並希望它在C中轉換爲ascii字符串。我怎麼能做到這一點?十六進制ASCII字符串轉換

+1

是不是一個十六進制字符串(如:' 「F00BA4」')ASCII字符串的特殊情況?或者正在使用EBCDIC? :) – pmg 2011-03-23 10:21:34

回答

13

你需要採取2(十六進制)字符在同一時間......然後計算int值 ,之後使焦炭轉化喜歡...

char d = (char)intValue;

每一個做到這一點

#include <stdio.h> 
#include <string.h> 

int hex_to_int(char c){ 
     int first = c/16 - 3; 
     int second = c % 16; 
     int result = first*10 + second; 
     if(result > 9) result--; 
     return result; 
} 

int hex_to_ascii(char c, char d){ 
     int high = hex_to_int(c) * 16; 
     int low = hex_to_int(d); 
     return high+low; 
} 

int main(){ 
     const char* st = "48656C6C6F3B"; 
     int length = strlen(st); 
     int i; 
     char buf = 0; 
     for(i = 0; i < length; i++){ 
       if(i % 2 != 0){ 
         printf("%c", hex_to_ascii(buf, st[i])); 
       }else{ 
         buf = st[i]; 
       } 
     } 
} 
2

幾個大字就像alphabe:在十六進制字符串

這個工程如果字符串字符只有0-9A-F 2chars ts i-o無法轉換爲相應的ASCII字符。 like in string'6631653064316f30723161'對應於fedora。但它給出了fedra

只是稍微修改hex_to_int()函數,它將適用於所有字符。 修改功能是

int hex_to_int(char c) 
{ 
    if (c >= 97) 
     c = c - 32; 
    int first = c/16 - 3; 
    int second = c % 16; 
    int result = first * 10 + second; 
    if (result > 9) result--; 
    return result; 
} 

現在嘗試它將適用於所有字符。

0

strtol()是你的朋友在這裏。第三個參數是您正在轉換的數字庫。

例子:

#include <stdio.h>  /* printf */ 
#include <stdlib.h>  /* strtol */ 

int main(int argc, char **argv) 
{ 
    long int num = 0; 
    long int num2 =0; 
    char * str. = "f00d"; 
    char * str2 = "0xf00d"; 

    num = strtol(str, 0, 16); //converts hexadecimal string to long. 
    num2 = strtol(str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal. 

    printf("%ld\n", num); 
    printf("%ld\n", num); 
} 
+0

所以沒有'itoa' ... – Yvain 2017-01-14 19:23:01

+0

@Yvain no。首先,用itoa()轉換是錯誤的。 'atoi()'只接受十進制輸入。 'atof'不接受十六進制(需要以上面第二個例子中的「0x」開頭,並且只能在C99或更高版本(如果有的話))下工作) – Baldrickk 2017-01-16 16:40:42

相關問題