hex.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. // $Id$
  15. #include <cassert>
  16. #include <iterator>
  17. #include <iomanip>
  18. #include <iostream>
  19. #include <sstream>
  20. #include <string>
  21. #include <vector>
  22. #include <exceptions/exceptions.h>
  23. #include <boost/foreach.hpp>
  24. #include <ctype.h>
  25. #include <stdint.h>
  26. #include "hex.h"
  27. using namespace std;
  28. namespace isc {
  29. namespace dns {
  30. static const char hexdigits[] = "0123456789ABCDEF";
  31. std::string
  32. encodeHex(const std::vector<uint8_t>& binary)
  33. {
  34. // calculate the resulting length. it should be twice the
  35. // original data length
  36. size_t len = (binary.size() * 2);
  37. std::ostringstream hex;
  38. BOOST_FOREACH(uint8_t octet, binary) {
  39. hex << hexdigits[octet >> 4] << hexdigits[octet & 0xf];
  40. }
  41. assert(len >= hex.str().length());
  42. return (hex.str());
  43. }
  44. void
  45. decodeHex(const std::string& hex, std::vector<uint8_t>& result)
  46. {
  47. result.clear();
  48. std::istringstream iss(hex);
  49. char c1, c2;
  50. uint8_t n;
  51. iss.width(1);
  52. if ((hex.size() % 2) == 1) {
  53. iss >> c2;
  54. const char* pos = strchr(hexdigits, toupper(c2));
  55. if (!pos) {
  56. isc_throw (BadHexString, "Invalid hex digit");
  57. }
  58. n = pos - hexdigits;
  59. result.push_back(n);
  60. }
  61. while (!iss.eof()) {
  62. iss >> c1 >> c2;;
  63. const char* pos1 = strchr(hexdigits, toupper(c1));
  64. const char* pos2 = strchr(hexdigits, toupper(c2));
  65. if (!pos1 || !pos2) {
  66. isc_throw (BadHexString, "Invalid hex digit");
  67. }
  68. n = (pos1 - hexdigits) << 4;
  69. n |= (pos2 - hexdigits);
  70. if (!iss.bad() && !iss.fail()) {
  71. result.push_back(n);
  72. }
  73. }
  74. }
  75. }
  76. }