Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cassert>
  4.  
  5. static char char2digit(char c) {
  6. if (c >= '0' && c <= '9')
  7. return (c - '0');
  8. if (c >= 'A' && c <= 'F')
  9. return (c - 'A' + 10);
  10. if (c >= 'a' && c <= 'f')
  11. return (c - 'a' + 10);
  12. assert(0);
  13. return 0;
  14. }
  15.  
  16. std::vector<char> set(const std::string &hexstring) {
  17. std::vector<char> bytes;
  18. size_t idx = 0;
  19. bool neg = false;
  20.  
  21. if (hexstring[idx] == '-') {
  22. neg = true;
  23. ++idx;
  24. }
  25. if (hexstring[idx] == '0' && hexstring[idx + 1] == 'x') {
  26. idx += 2;
  27. }
  28. size_t size = hexstring.size();
  29. assert((size - idx) > 0);
  30.  
  31. if ((size - idx) % 2 != 0) {
  32. char c = char2digit(hexstring[idx++]);
  33. bytes.push_back(c);
  34. }
  35.  
  36. for (; idx < size; ) {
  37. char c = char2digit(hexstring[idx++]) << 4;
  38. c += char2digit(hexstring[idx++]);
  39. bytes.push_back(c);
  40. }
  41. return bytes;
  42. }
  43.  
  44. int main() {
  45. auto v = set("0xaba");
  46. for (const auto b : v) {
  47. std::cout << static_cast<int>(static_cast<unsigned char>(b)) << "\n";
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement