1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef PANDA_LIBPANDABASE_UTILS_UTILS_H_ 17 #define PANDA_LIBPANDABASE_UTILS_UTILS_H_ 18 19 namespace panda { 20 // ---------------------------------------------------------------------------- 21 // General helper functions 22 23 // Returns the value (0 .. 15) of a hexadecimal character c. 24 // If c is not a legal hexadecimal character, returns a value < 0. HexValue(uint32_t c)25inline int32_t HexValue(uint32_t c) 26 { 27 constexpr uint32_t BASE16 = 16; 28 constexpr uint32_t BASE10 = 10; 29 constexpr uint32_t MASK = 0x20; 30 31 c -= '0'; 32 if (static_cast<unsigned>(c) < BASE10) { 33 return c; 34 } 35 // NOLINTNEXTLINE(hicpp-signed-bitwise) 36 c = (c | MASK) - ('a' - '0'); 37 if (static_cast<unsigned>(c) < (BASE16 - BASE10)) { 38 return c + BASE10; 39 } 40 return -1; 41 } 42 43 } // namespace panda 44 45 #endif // PANDA_LIBPANDABASE_UTILS_UTILS_H_ 46