unsigned char *值为十六进制

时间:2016-06-10 11:53:25

标签: c++ c

我有一个典型的用例,我需要将unsigned char值转换为十六进制。

例如,

unsigned char *pBuffer = (unsigned char *)pvaluefromClient //where pvaluefromclient is received from a client

pBuffer的长度为32个字节,它保存的值如下,

(gdb) p pBuffer 
$5 = (unsigned char *) 0x7fd4b82cead0 "EBA5F7304554DCC3702E06182AB1D487"
(gdb) n

步骤1:我需要按如下方式拆分此pBuffer值,

{EB,A5,F7,30,45,54,DC,C3,70,2E,06,18,2A,B1,D4,87 }

第2步:我需要将上面的分割值转换为十进制,如下所示,

const unsigned char pConvertedBuffer[16] = {
    235,165,247,48,69,84,220,195,112,46,6,24,42,177,212,135
};

关于如何实现STEP1和STEP2的任何想法?对此的任何帮助都将受到高度赞赏

3 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

unsigned char *pBuffer = (unsigned char *)pvaluefromClient //where valuefromclient is received from a client

int i, j;
unsigned char target[16]
for(i=0;i<32;i+=2)
{
   sscanf((char*)&pBuffer[i], "%02X", &j);
   target[i/2] = j;
}

答案 1 :(得分:0)

您可以创建一个函数,它将两个无符号字符作为参数,并返回另一个unsigned char。这两个参数是字符(第一个字节的E和B)。返回的值将是字节的数值。

逻辑是:

unsigned char hex2byte(unsigned char uchar1, unsigned char uchar2) {
    unsigned char returnValue = 0;

    if((uchar1 >= '0') && (uchar1 <= '9')) {
        returnValue = uchar1 - 0x30; //0x30 = '0'
    }
    else if((uchar1 >= 'a') && (uchar1 <= 'f')) {
        returnValue = uchar1 - 0x61 + 0x0A; //0x61 = 'a'
    }
    else if((uchar1 >= 'A') && (uchar1 <= 'F')) {
        returnValue = uchar1 - 0x41 + 0x0A; //0x41 = 'A'
    }

    if((uchar2 >= '0') && (uchar2 <= '9')) {
        returnValue = (returnValue <<8) + (uchar2 - 0x30); //0x30 = '0'
    }
    else if((uchar2 >= 'a') && (uchar2 <= 'f')) {
        returnValue = (returnValue <<8) + (uchar2 - 0x61 + 0x0A); //0x61 = 'a'
    }
    else if((uchar2 >= 'A') && (uchar1 <= 'F')) {
        returnValue = (returnValue <<8) + (uchar2 - 0x41 + 0x0A); //0x41 = 'A'
    }        

    return returnValue;
}

基本思想是计算字符的数值并重新组合两个字符的数字(因此位移)

我很确定在这里和那里有多个比我更优雅的解决方案。

答案 2 :(得分:0)

void Conversion(char *pBuffer, int *ConvertedBuffer)
{
    int j = 0;
    for(int i = 0; i < 32; i += 2)
    {
        std::stringstream ss;
        char sz[4] = {0};

        sz[0] = pBuffer[i];
        sz[1] = pBuffer[i+1];
        sz[2] = 0;

        ss << std::hex << sz;
        ss >> ConvertedBuffer[j];
        ++j;
    }
}
int  main()
{
    char Buffer[] = "EBA5F7304554DCC3702E06182AB1D487";
    int ConvertedBuffer[16];
    Conversion(Buffer, ConvertedBuffer);
    for(int i = 0; i < 16; ++i)
    {
        cout << ConvertedBuffer[i] << " ";
    }
    return 0;
}

//output:
235 165 247 48 69 84 220 195 112 46 6 24 42 177 212 135