• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025-2025 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// import buffer from "@ohos.buffer"
17
18namespace utils {
19export function hexStrToUint8Array(data: string): Uint8Array {
20  // return new Uint8Array(buffer.from(data, 'hex').buffer);
21  if (data.length % 2 !== 0) {
22    throw new Error("Invalid hex string");
23  }
24  const array = new Uint8Array(data.length / 2);
25  for (let i = 0; i < data.length; i += 2) {
26    array[i / 2] = parseInt(data.substring(i, i + 2), 16);
27  }
28  return array;
29}
30
31export function stringToUint8Array(str: string): Uint8Array {
32  // return new Uint8Array(buffer.from(str, 'utf-8').buffer);
33  const array = new Uint8Array(str.length);
34  for (let i = 0; i < str.length; i++) {
35    array[i] = str.charCodeAt(i);
36  }
37  return array;
38}
39
40export function uint8ArrayToHexStr(data: Uint8Array): string {
41  // return buffer.from(data).toString('hex').toUpperCase();
42  let str = '';
43  for (let i = 0; i < data.length; i++) {
44    let num: Number = new Number(data[i])
45    str += num.toString(16).padStart(2, '0');
46  }
47  return str;
48}
49} // namespace utils
50
51export default utils;
52