parse_hexstring.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include "test/core/util/parse_hexstring.h"
  19. #include <grpc/support/log.h>
  20. grpc_slice parse_hexstring(const char* hexstring) {
  21. size_t nibbles = 0;
  22. const char* p = nullptr;
  23. uint8_t* out;
  24. uint8_t temp;
  25. grpc_slice slice;
  26. for (p = hexstring; *p; p++) {
  27. nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f');
  28. }
  29. GPR_ASSERT((nibbles & 1) == 0);
  30. slice = grpc_slice_malloc(nibbles / 2);
  31. out = GRPC_SLICE_START_PTR(slice);
  32. nibbles = 0;
  33. temp = 0;
  34. for (p = hexstring; *p; p++) {
  35. if (*p >= '0' && *p <= '9') {
  36. temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0');
  37. nibbles++;
  38. } else if (*p >= 'a' && *p <= 'f') {
  39. temp =
  40. static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10);
  41. nibbles++;
  42. }
  43. if (nibbles == 2) {
  44. *out++ = temp;
  45. nibbles = 0;
  46. }
  47. }
  48. return slice;
  49. }