HarmonyOS 进制转换问题?

将16进制字符串转换为Uint8Array的方法是什么?

阅读 463
1 个回答

当前暂不支持16进制字符串直接转换为Uint8Array,可以将16进制字符串转换成字符串进而通过已有方法将其间接转换成Uint8Array,参考示例:

import { promptAction } from '@kit.ArkUI';
import buffer from '@ohos.buffer';
import { util } from '@kit.ArkTS';


@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  hexToString(hex: string): string {
    let hexString = hex;
    if (hex.indexOf('0x') === 0) {
      hexString = hex.substring(2, hex.length);
    }
    let buf = buffer.from(hex, 'hex');
    return buf.toString();
  }

  stringToHex(input: string): string {
    return Array.from(input)
      .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
      .join('');
  }

  build() {
    Row() {
      Column() {
        // 应用退出时会保存当前结果。重新启动后,会显示上一次的保存结果
        Button(`点击`)
          .onClick(() => {

            //字符串转16进制

            // let param = buffer.from("测试一下啊").toString('hex')
            // let param = buffer.from("测试一下啊ewedwefaefa").toString('hex')
            let param = buffer.from("ewedwefaefa").toString('hex')

            console.log(`16进制:${param}`)


            //16进制转字符串
            let str = this.hexToString(param)
            console.log(`str:${str}`)

            let array = stringToArray(str)
            console.log(`Uint8Array:${JSON.stringify(array)}`)

            let arrayStr = arrayToString(array)
            console.log(`Uint8Array转字符串:${JSON.stringify(arrayStr)}`)


            let param2 = buffer.from(arrayStr).toString('hex')
            console.log(`16进制2:${param2}`)


            promptAction.showToast({ message: `方法已执行,请查看控制台日志信息` })
          })
      }.justifyContent(FlexAlign.Center)
      .width("100%")
      .height("100%")
    }
  }
}

function stringToArray(str: string): Uint8Array {
  let textEncoder = new util.TextEncoder();
  return textEncoder.encodeInto(str);
}

function arrayToString(arr: Uint8Array): string {
  let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true });
  let str = textDecoder.decodeWithStream(arr, { stream: false })
  return str;
}
logo
HarmonyOS
子站问答
访问
宣传栏