Uint8Array和string之间的相互转换

Uint8Array和string之间的相互转换

HarmonyOS
2024-06-11 20:18:16
4224浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
快乐小肥仔

1、首先,在convertStrToUint8Arr 方法中进行类型判断,如果输入参数是 Date 类型则返回空;

2、检查字符串是否为空或者只包含空白字符,如果是则返回空;

3、最后使用 TextEncoder 对象将字符串编码为 Uint8Array,并返回结果。

4、通过 convertUint8ArrToStr 方法将 Uint8Array 转换为字符串,如果输入参数不是 Uint8Array 类型则返回空字符串;最后使用 TextDecoder 对象将 Uint8Array 解码为字符串,并返回结果。

参考代码如下:

convertStrToUint8Arr(source: string | Date): Uint8Array | null { 
  //类型判断 
  if (this.typeChecker.isDate(source)) { 
    this.paramCheckMsg = 'source is not a string' 
    return null; 
  } 
 
  let sourceStr = source as string; 
  //检查转换后的字符串是否为空或者只包含空白字符 
  if (sourceStr == '' || sourceStr.trim() == '') { 
    this.paramCheckMsg = 'encodeStrToUint8Arr param is empty' 
    return null; 
  } 
  // 
  return new util.TextEncoder().encodeInto(sourceStr); 
} 
 
convertUint8ArrToStr(arr: Uint8Array | object): string { 
  //创建了一个 TextDecoder 对象,用于解码 Uint8Array 数组为字符串。这里指定了字符编码为 UTF-8 
  //ignoreBOM:是否忽略BOM(byte order marker)标记,默认值为false ,表示解码结果包含BOM标记。 
  let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); 
  // 使用 typeChecker.isUint8Array(arr) 来检查参数 arr 是否为 Uint8Array 类型的数组。如果是,则使用 TextDecoder 对象将数组解码为字符串并返回;否则返回空字符串。 
  return this.typeChecker.isUint8Array(arr) ? textDecoder.decode(arr as Uint8Array, {stream: false}) : ""; 
} 
 
let sourceStr = 'happy everyday'; 
// 调用 convertStrToUint8Arr 方法将字符串转换为 Uint8Array 
let buffer: Uint8Array | null = this.convertStrToUint8Arr(sourceStr); 
console.debug("convertStrToUint8Arr buffer = " + buffer); 
// 判断返回值 
if (buffer == null) return; 
// 调用 convertUint8ArrToStr 方法将 Uint8Array 转换为字符串 
let retStr: string = this.convertUint8ArrToStr(buffer); 
console.debug("convertUint8ArrToStr retStr = " + retStr);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
分享
微博
QQ
微信
回复
2024-06-12 16:54:57


相关问题
HarmonyOS string怎么与Uint8Array互转
1504浏览 • 1回复 待解决
HarmonyOS stringUint8Array
763浏览 • 2回复 待解决
Uint8Array 如何直接转为String or Json
3512浏览 • 1回复 待解决
HarmonyOS Uint8Array转成string后出现乱码
922浏览 • 2回复 待解决
HarmonyOS 中Uint8Array
658浏览 • 1回复 待解决
pxvp之间如何相互转换
4472浏览 • 1回复 待解决
Uint8Array如何转成ArrayBuffer
2075浏览 • 1回复 待解决
ArrayBuffer怎么转Uint8Array
1099浏览 • 1回复 待解决
HarmonyOS 录音发送Uint8Array
452浏览 • 1回复 待解决
HarmonyOS Uint8Array转16进制
622浏览 • 2回复 待解决
HarmonyOS ArrayBuffer如何转成Uint8Array
763浏览 • 1回复 待解决
Uint8Array是@Sendable类吗?
839浏览 • 1回复 待解决
HarmonyOS uint8Array转字符串
874浏览 • 1回复 待解决
HarmonyOS Uint8Array怎么正确转ArrayBuffer
2218浏览 • 1回复 待解决
HarmonyOS List<number>怎么转Uint8Array
636浏览 • 1回复 待解决
如何将Uint8Array转ArrayBuffer?
944浏览 • 1回复 待解决
HarmonyOS socket.TLSSocket发送Uint8Array对象
495浏览 • 1回复 待解决