【问题标题】:Convert to ascii to hex without using print在不使用 print 的情况下将 ascii 转换为 hex
【发布时间】:2015-04-20 05:49:35
【问题描述】:

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

到目前为止,我所知道的是,如果您将 char 转换为 int,您将获得 ascii 值,然后我可以获得十六进制值,这让我很困惑。

【问题讨论】:

  • 什么是print?在 C 中没有这个名字。你的意思是 printf
  • 您不需要将 char 转换为 int。 char 是 C 中的整数类型。
  • 您可以逐个字符地遍历字符串。
  • 所有非常有用的 cmets。谢谢

标签: c hex


【解决方案1】:

这是一个的方法,一个完整的程序,但“肉”在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;
}

【讨论】:

  • 我想知道她/他真正想要的是uint64_t result=0x61622e6332。这个问题在这一点上根本不清楚。
  • @user3386109,可能是这样,但他们声明 "ab.c2" --&gt; "61622e6332" 的事实似乎表明了 string 结果。此外,他们声明“不使用 print”(大概是 printf)并且没有理智的方法可以从带有 printf 的字符串中获取整数值 :-)
  • 绿色检查确认:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2015-10-30
  • 1970-01-01
  • 2014-09-05
  • 2013-08-09
  • 2022-01-04
相关资源
最近更新 更多