将char数组转换为十六进制数组(C ++) [英] Convert char array to hex array (C++)

查看:291
本文介绍了将char数组转换为十六进制数组(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是将字符数组转换为十六进制数,我需要从字符数组中提取2个字符并将其转换为十六进制数.

My problem is converting array of chars to array of hexadecimal numbers, i need to take 2chars from char array and conver them into one hex number.

这是我的输入:

unsigned char text [1024]= "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";

这就是我所需要的:

unsigned char hexval[1024] = {0x06, 0xfb, 0x74, 0x05, 0xeb, 0xa8, 0xd9, 0xe9, 0x4f, 0xb1, 0xf2, 0x8f, 0x0d, 0xd2, 0x1f, 0xde, 0xc5, 0x5f, 0xd5, 0x47, 0x50, 0xee, 0x84, 0xd9, 0x5e, 0xcc, 0xcf, 0x2b, 0x1b, 0x48};

我发现函数 sscanf()可以解决我的问题,但是我不知道如何在我的输入数组上正确使用它.

I found function sscanf() that could solve my problem but i dont know how to properly use it onmy input array.

我如何实现这种转换?

推荐答案

一些简单的实现

unsigned char text[1024] = "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";
unsigned char result[512];

int size = 60;

assert(size % 2 == 0);

for (int i = 0; i + 1 < size; i += 2)
{
    std::string s(text + i, text + i + 2);
    auto x = std::stoi(s, 0, 16);
    result[i / 2] = x;
}
// or
for (int i = 0; i + 1 < size; i += 2)
{
    unsigned char c1 = *(text + i);
    unsigned char c2 = *(text + i + 1);
    char buffer[] = { c1, c2, 0 };
    auto x = std::strtol(buffer, 0, 16);
    result[i / 2] = x;
}

在这种情况下,结果是输入的一半大小.两个字符导致结果中的一个值.如果这是时间紧迫的例程,则可以编写一个数字中的两个字符自己的转换.

In this case the result is the half size of the input. Two chars are leading to one value in the result. If this is a time critical routine you may write your own conversion from two chars in a number.

这篇关于将char数组转换为十六进制数组(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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