-1

I have a string storing 16 hex chars. For example:

const char* arr = "DD2B23B62AC245DA";

I need to write those chars into a binary file in a format of 8 bytes. Each byte is represented by two hex chars in their hex value. The way I did it is:

unsigned char  hexArr[8];
hexArr[0] = 0xDD;
hexArr[1] = 0x2B;
hexArr[2] = 0x23;
...

The problem in that way is that it is hard-coded, and I need to be able to get this array as an input and then to fill the hexArr array.

When I copy the array itself it sets the hex value of the char D instead of D as a hexadecimal value. Any help how can I do that?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1016179
  • 599
  • 3
  • 10
  • 24

2 Answers2

1

The easiest way is in my opinion to do the conversion yourself by code:

std::vector<unsigned char> parseHex(const char *s) {
    std::vecotr<unsigned char> result;
    int acc=0, n=0;
    for (int i=0; s[i]; i++) {
        acc <<= 4;
        if (s[i] >= '0' && s[i] <= '9')      acc += (s[i] - '0');
        else if (s[i] >= 'a' && s[i] <= 'f') acc += 10 + (s[i] - 'a');
        else if (s[i] >= 'A' && s[i] <= 'F') acc += 10 + (s[i] - 'A');
        else throw std::runtime_error("invalid hex literal digit");
        if (++n == 2) {
            result.push_back(acc);
            acc = n = 0;
        }
    }
    if (n) throw std::runtime_error("invalid hex literal length");
    return result;
}
6502
  • 112,025
  • 15
  • 165
  • 265
0

Though the answer above is accepted, I think this one is more elegant:

int chartoint(char c) {
  const char* buf = "0123456789abcdef";
  const char* ptr = std::strchr(buf, std::tolower(c));

  if (!ptr)
    throw std::runtime_error("Not a hex digit:" + c);
  return ptr - buf;
}

void cast(const char* arr, std::vector<unsigned char>* chvec) {
  size_t arrlen = strlen(arr);
  if (arrlen & 1) {
    throw std::runtime_error(std::string("odd string length:") + arr);
  }

  while (*arr) {
    int val = chartoint(*arr++) << 4;
    val += chartoint(*arr++);
    chvec->push_back(val);
  }
}
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42