Uint8Array 是常用的数据格式,通常用于网络请求,文件读取。因为数据的组织是8位Uint的Array,里面存的是数字,在开发调试时不是很方便。
在实时的使用时,也需要对其进行解码,转为具体的字符。
在早期的鸿蒙版本,使用TextDecoder的decode方法进行转码,但该方法在从API version 7开始支持,从API version 9开始废弃,官方建议使用decodeToString替代。decodeToString方法在API 12开始支持,仅支持HarmonyOS NEXT的App,可以直接升级了。
下面的代码为使用decode方法及decodeToString进行解码的代码示例
// 原内容,俩毛豆 , 是不是不易查看
let uint8Data = new Uint8Array( [228,191,169,230,175,155,232,177,134]);
// 使用decode
let decoder: util.TextDecoder = new util.TextDecoder();
const decodeStr = decoder.decode(new Uint8Array(uint8Data));
console.info("tran decodeStr = " + decodeStr); // tran decodeStr = 俩毛豆
// 使用decodeToString
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
};
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let decodeToStr = textDecoder.decodeToString(uint8Data, decodeToStringOptions);
console.info("tran decodeToString = " + decodeToStr); // tran decodeToString = 俩毛豆