0

I have string hex ex. std :: string x="68656c6c6f" ; I want to convert it to array of characters each element in the array is 2 hexadecimal numbers ex.

char c[5]={0x68,0x65,0x6c,0x6c,0x6f} ;

I'm using c++, and I already have the string of hexadecimal numbers and I don't have the option to read the values as an array of character. I can't use scanf("%x",&c[i]);

  • You should show what you have tried yourself, or what you have researched, or why you are stumped (this is rather easy problem with numerous possible solutions). Now your "question" is either "please do my work for me" or "I want some vague hints on how to do this", and neither is a good fit for Stack Overflow. – hyde Aug 07 '17 at 17:57
  • 2
    Also, C or C++? They are different languages. Remove one tag, please. `string` is C++, if you meant `std::string`. – hyde Aug 07 '17 at 18:01
  • Hint: look into `std::stoi` and similars. – Emerald Weapon Aug 07 '17 at 18:17
  • Not very universal - what about "4ed3478cdab4ed3478cdab4ed3478cdab4ed3478cdab4ed3478cdab4ed3478cdab4ed3478cdab" ? – 0___________ Aug 07 '17 at 18:18
  • @PeterJ I am simply suggesting a starting point that can lead to a more general solution provided some extra effort. – Emerald Weapon Aug 07 '17 at 18:22

1 Answers1

0

C (will work in C++ as well)

int cnvhex(const char *num, int *table)
{
    const char *ptr;
    int index = (num == NULL || table == NULL) * -1;


    size_t len = strlen(num);

    ptr = num + len - 2;
    if (!index)
    {
        for (index = 0; index < len / 2; index++)
        {
            char tmp[3] = { 0, };

            strncpy(tmp, ptr, 2);
            if (sscanf(tmp, "%x", table + index) != 1)
            {
                index = -1;
                break;
            }
            ptr -= 2;
        }
        if (index != -1 && (len & 1))
        {
            char tmp[2] = { *num, 0};

            if(sscanf(tmp, "%x", table + index++) != 1) index = -1;
        }
    }
    return index;
}
0___________
  • 60,014
  • 4
  • 34
  • 74