1 /* 2 * Copyright 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "host/commands/casimir_control_server/hex.h" 18 19 #include "common/libs/utils/result.h" 20 21 namespace cuttlefish { 22 namespace { 23 ByteNumber(char x)24static int ByteNumber(char x) { 25 x = tolower(x); 26 if ('0' <= x && x <= '9') { 27 return x - '0'; 28 } else if ('a' <= x && x <= 'f') { 29 return x - 'a' + 10; 30 } 31 return -1; 32 } 33 34 } // namespace 35 HexToBytes(const std::string & hex_string)36Result<std::vector<uint8_t>> HexToBytes(const std::string& hex_string) { 37 CF_EXPECT(hex_string.size() % 2 == 0, 38 "Failed to parse input. Must be even size"); 39 40 int len = hex_string.size() / 2; 41 std::vector<uint8_t> out(len); 42 for (int i = 0; i < len; i++) { 43 int num_h = ByteNumber(hex_string[i * 2]); 44 int num_l = ByteNumber(hex_string[i * 2 + 1]); 45 CF_EXPECT(num_h >= 0 && num_l >= 0, 46 "Failed to parse input. Must only contain [0-9a-fA-F]"); 47 out[i] = num_h * 16 + num_l; 48 } 49 50 return out; 51 } 52 53 } // namespace cuttlefish 54