Skip to content

Instantly share code, notes, and snippets.

@prehistoricpenguin
Created March 27, 2014 08:22
Show Gist options
  • Select an option

  • Save prehistoricpenguin/9802850 to your computer and use it in GitHub Desktop.

Select an option

Save prehistoricpenguin/9802850 to your computer and use it in GitHub Desktop.
"0123456789abcdef" - > 0x12 0x34 0x56 0x78 ...
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <string>
#include <vector>
#include <stdexcept>
#include <iostream>
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);
}
}
void test() {
const char* arr = "DD2B23B62AC245DA";
char buf[100];
std::vector<unsigned char> vec;
cast(arr, &vec);
for (auto ch : vec) printf("%02x ", ch);
}
int main() {
test();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment