Created
March 27, 2014 08:22
-
-
Save prehistoricpenguin/9802850 to your computer and use it in GitHub Desktop.
"0123456789abcdef" - > 0x12 0x34 0x56 0x78 ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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