十六进制到ascii字符串转换

时间:2011-03-23 09:27:20

标签: c

我有一个十六进制字符串,希望它在C中转换为ascii字符串。我怎么能完成这个?

4 个答案:

答案 0 :(得分:13)

你需要同时取2个(十六进制)字符...然后计算int值 之后使char转换成......

char d = (char)intValue;

对十六进制字符串中的每个2个字符执行此操作

如果字符串字符仅为0-9A-F:

,则此方法有效
#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];
                }
        }
}

答案 1 :(得分:2)

字母i-o等少数字符无法转换为相应的ASCII字符。 比如字符串'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;
}

现在尝试它将适用于所有角色。

答案 2 :(得分:2)

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);
}

答案 3 :(得分:0)

如果我理解正确,您想知道如何将编码为十六进制字符串的字节转换为ASCII文本形式,例如“ 537461636B”将被转换为“堆栈”,在这种情况下,以下代码应解决你的问题。

尚未运行任何基准测试,但我认为这不是效率的顶峰。

static char ByteToAscii(const char *input) {
  char singleChar, out;
  memcpy(&singleChar, input, 2);
  sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
  return out;
}

int HexStringToAscii(const char *input, unsigned int length,
                            char **output) {
  int mIndex, sIndex = 0;
  char buffer[length];
  for (mIndex = 0; mIndex < length; mIndex++) {
    sIndex = mIndex * 2;
    char b = ByteToAscii(&input[sIndex]);
    memcpy(&buffer[mIndex], &b, 1);
  }
  *output = strdup(buffer);
  return 0;
}
相关问题