不使用print将ascii转换为十六进制

时间:2015-02-19 01:01:28

标签: c hex

所以我希望能够以某种方式将字符串更改为十六进制,如下所示:“ab.c2” - > “61622e6332”。我在网上找到的所有帮助都显示了如何使用print进行操作,但我不想使用print,因为它不存储十六进制值。

到目前为止我所知道的是,如果你拿一个char并将它转换成一个int,你就得到了ascii值,并且我可以得到十六进制,这就是我难倒的地方。

1 个答案:

答案 0 :(得分:2)

这是一种方式,一个完整的程序,但“肉”在tohex函数中:

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

char * tohex (unsigned char *s) {
    size_t i, len = strlen (s) * 2;

    // Allocate buffer for hex string result.
    // Only output if allocation worked.

    char *buff = malloc (len + 1);
    if (buff != NULL) {
        // Each char converted to hex digit string
        // and put in correct place.

        for (i = 0; i < len ; i += 2) {
            sprintf (&(buff[i]), "%02x", *s++);
        }
    }

    // Return allocated string (or NULL on failure).

    return buff;
}

int main (void) {
    char *input = "ab.c2";

    char *hexbit = tohex (input);
    printf ("[%s] -> [%s]\n", input, hexbit);
    free (hexbit);

    return 0;
}

当然有其他方法可以实现相同的结果,例如,如果您可以确保提供足够大的缓冲区,则可以避免内存分配,例如:

#include <stdio.h>

void tohex (unsigned char *in, char *out) {
    while (*in != '\0') {
        sprintf (out, "%02x", *in++);
        out += 2;
    }
}

int main (void) {
    char input[] = "ab.c2";
    char output[sizeof(input) * 2 - 1];
    tohex (input, output);
    printf ("[%s] -> [%s]\n", input, output);
    return 0;
}
相关问题