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 19 #include "test/core/util/parse_hexstring.h" 20 #include <grpc/support/log.h> 21 parse_hexstring(const char * hexstring)22grpc_slice parse_hexstring(const char* hexstring) { 23 size_t nibbles = 0; 24 const char* p = nullptr; 25 uint8_t* out; 26 uint8_t temp; 27 grpc_slice slice; 28 29 for (p = hexstring; *p; p++) { 30 nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f'); 31 } 32 33 GPR_ASSERT((nibbles & 1) == 0); 34 35 slice = grpc_slice_malloc(nibbles / 2); 36 out = GRPC_SLICE_START_PTR(slice); 37 38 nibbles = 0; 39 temp = 0; 40 for (p = hexstring; *p; p++) { 41 if (*p >= '0' && *p <= '9') { 42 temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0'); 43 nibbles++; 44 } else if (*p >= 'a' && *p <= 'f') { 45 temp = 46 static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10); 47 nibbles++; 48 } 49 if (nibbles == 2) { 50 *out++ = temp; 51 nibbles = 0; 52 } 53 } 54 55 return slice; 56 } 57