如何将字符转换为十六进制存储在uint8_t形式? [英] How to convert char to hex stored in uint8_t form?

查看:751
本文介绍了如何将字符转换为十六进制存储在uint8_t形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这些变量,

Suppose I have these variables,

const uint8_t ndef_default_msg[33] = {
    0xd1, 0x02, 0x1c, 0x53, 0x70, 0x91, 0x01, 0x09,
    0x54, 0x02, 0x65, 0x6e, 0x4c, 0x69, 0x62, 0x6e,
    0x66, 0x63, 0x51, 0x01, 0x0b, 0x55, 0x03, 0x6c,
    0x69, 0x62, 0x6e, 0x66, 0x63, 0x2e, 0x6f, 0x72,
    0x67
};
uint8_t *ndef_msg;
char *ndef_input = NULL;

如何转换 ndef_input (这是只是一个纯文本,如你好)十六进制并保存到 ndef_msg
正如你所看到的 ndef_default_msg 是十六进制格式。 ndef_msg 中的数据也应该是这样的。

How can I convert ndef_input (which is just a plain text, like "hello") to hex and save into ndef_msg? As you can see ndef_default_msg is in hex form. Data inside ndef_msg should be something like that as well.

在原始程序中有一点背景(<一个href =http://pastebin.com/VY5ynNDw =nofollow>源代码),程序将打开一个文件,获取数据并将其放入 ndef_msg ,然后将其写入卡片。但我不明白它是如何将数据转换为十六进制的。

A bit of background, in the original program (source code), the program will open a file, get the data and put it inside ndef_msg, which then will be written into a card. But I don't understand how it can take the data and convert to hex.

我想简化程序,所以它会直接询问用户的文本(​​而不是询问对于一个文件)。

I want to simplify the program so it will directly ask user for text (instead of asking for a file).

推荐答案

为什么不直接将它读入ndef_msg,(减去\0,如果它假设是一个纯数组)。十六进制只是为了演示,你可以刚刚选择小数或八进制,而不会对内容产生影响。

Why not read it into ndef_msg directly, (minus the \0 if it suppose to be a pure array). The hex are just for presentation, you could have just picked decimal or octal with no consequence for the content.

void print_hex(uint8_t *s, size_t len) {
    for(int i = 0; i < len; i++) {
        printf("0x%02x, ", s[i]);
    }
    printf("\n");
}

int main()
{
    uint8_t ndef_msg[34] = {0};

    scanf("%33s", ndef_msg);
    print_hex(ndef_msg, strlen((char*)ndef_msg));


    return 0;
}

您可能需要以不同的方式处理字符串的读取,以允许空格和或许忽略 \0 ,这只是为了说明我的观点。

You probably need to handle the reading of the string differently to allow for whitespace and perhaps ignore \0, this is just to illustrate my point.

这篇关于如何将字符转换为十六进制存储在uint8_t形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆