• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2023 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
16import buffer from '@ohos.buffer';
17
18function stringToUint8Array(str: string) {
19  let arr: number[] = [];
20  for (let i = 0, j = str.length; i < j; ++i) {
21    arr.push(str.charCodeAt(i));
22  }
23  return new Uint8Array(arr);
24}
25
26function uint8ArrayToString(fileData: Uint8Array): string {
27  let dataString = "";
28  for (let i = 0; i < fileData.length; i++) {
29    dataString += String.fromCharCode(fileData[i]);
30  }
31  return dataString;
32}
33
34function hexToUint8Array(hexString: string) {
35  const length: number = hexString.length;
36  if (length % 2 !== 0) {
37    throw new Error('Invalid input');
38  }
39  let a = '[';
40  const uint8Array = new Uint8Array(length / 2);
41  for (let i = 0; i < length; i += 2) {
42    const byteValue = parseInt(hexString[i] + hexString[i+1], 16);
43    uint8Array[i/2] = byteValue;
44    a = a + byteValue + ','
45  }
46  return uint8Array;
47}
48
49function uint8ArrayToHex(data: Uint8Array) {
50  return buffer.from(data).toString('hex');
51}
52
53export {
54  stringToUint8Array, uint8ArrayToString, hexToUint8Array, uint8ArrayToHex
55}