1 /*
2  * Copyright (c) 2024 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 #include "string_utils.h"
17 
18 namespace OHOS {
19 namespace HDI {
20 namespace Location {
21 static constexpr uint8_t HEX_OFFSET = 4;
22 static constexpr uint8_t STEP_2BIT = 2;
23 
StringUtils()24 StringUtils::StringUtils() {}
25 
~StringUtils()26 StringUtils::~StringUtils() {}
27 
HexCharToInt(char c)28 uint16_t StringUtils::HexCharToInt(char c)
29 {
30     const uint8_t decimal = 10;
31     if (c >= '0' && c <= '9') {
32         return (c - '0');
33     }
34     if (c >= 'A' && c <= 'F') {
35         return (c - 'A' + decimal);
36     }
37     if (c >= 'a' && c <= 'f') {
38         return (c - 'a' + decimal);
39     }
40     return 0;
41 }
42 
HexToByteVector(const std::string & str)43 std::vector<uint8_t> StringUtils::HexToByteVector(const std::string &str)
44 {
45     std::vector<uint8_t> ret;
46     int sz = static_cast<int>(str.length());
47     if (sz <= 0) {
48         return ret;
49     }
50     for (int i = 0; i < (sz - 1); i += STEP_2BIT) {
51         auto temp = static_cast<uint8_t>((HexCharToInt(str.at(i)) << HEX_OFFSET) | HexCharToInt(str.at(i + 1)));
52         ret.push_back(temp);
53     }
54     return ret;
55 }
56 
57 } // namespace Location
58 } // namespace HDI
59 } // namespace OHOS