鸿蒙OS开发问题:(ArkTS) 【解决中文乱码 string2Uint8Array、uint8Array2String】

电子说

1.3w人已加入

描述

在进行base64编码中,遇到中文如果不进行处理一定会出现乱码

let result1: string = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(('一二三四五六七八九十123')))
  LogUtils.i("result1 = " + result1);
  let result2: string = CryptoJS.enc.Base64.parse(result1).toString(CryptoJS.enc.Utf8)
  LogUtils.i("result2 = " + result2);复制

输出结果:

┌────────────────────────────────────────────────────────
 ├1 result1 = 5LiA5LqM5LiJ5Zub5LqU5YWt5LiD5YWr5Lmd5Y2BMTIz
└────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────
├1 result2 = ä¸äºä¸åäºåÂ
└────────────────────────────────────────────────────────

刚开始在编码的时候就已经出问题了,使用CryptoJS 框架 截止发稿前就一直存在这个问题,后面只有自己手撸工具类:

import util from '@ohos.util';

class StringUtils {
  /**
   * string转Uint8Array
   * @param value
   * @returns
   */
  string2Uint8Array1(value: string): Uint8Array {
    if (!value) return null;
    //
    let textEncoder = new util.TextEncoder();
    //获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码
    return textEncoder.encodeInto(value)
  }
  /**
   * string转Uint8Array
   * @param value 包含要编码的文本的源字符串
   * @param dest 存储编码结果的Uint8Array对象实例
   * @returns 它返回一个包含读取和写入的两个属性的对象
   */
  string2Uint8Array2(value: string, dest: Uint8Array) {
    if (!value) return null;
    if (!dest) dest = new Uint8Array(value.length);
    let textEncoder = new util.TextEncoder();
    //read:它是一个数值,指定转换为 UTF-8 的字符串字符数。如果 uint8Array 没有足够的空间,这可能小于 src.length(length of source 字符串)。
    //dest:也是一个数值,指定存储在目标 Uint8Array 对象 Array 中的 UTF-8 unicode 的数量。它总是等于阅读。
    textEncoder.encodeIntoUint8Array(value, dest)
    // let result = textEncoder.encodeIntoUint8Array(value, dest)
    // result.read
    // result.written
  }
  /**
   * Uint8Array 转  String
   * @param input
   */
  uint8Array2String(input: Uint8Array) {
    let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
    return textDecoder.decodeWithStream(input, { stream: false });
  }
  /**
   * ArrayBuffer 转  String
   * @param input
   * @returns
   */
  arrayBuffer2String(input: ArrayBuffer) {
    return this.uint8Array2String(new Uint8Array(input))
  }
}

export default new StringUtils()

示例代码:

let globalPlainText = ""
globalPlainText += "一二三四五六七八九十"
  globalPlainText += "SDK向DevEco Studio提供全量API,DevEco Studio识别开发者项目中选择的设备形态,找到该设备的支持能力集,筛选支持能力集包含的API并提供API联想"

  let dealStr = StringUtils.string2Uint8Array1(globalPlainText)
  let base64Str = base64.encode(dealStr)
  LogUtils.i("base64 = " + base64Str);
  //
  let arr1: ArrayBuffer = base64.decode(base64Str)
  LogUtils.i("result1 = " + StringUtils.arrayBuffer2String(arr1));复制
鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。或+mau123789学习,是v喔

鸿蒙OS

运行结果:

鸿蒙OS

TextEncoder源码(部分API在since 9 已废弃):

/**
     * The TextDecoder interface represents a text decoder.
     * The decoder takes the byte stream as the input and outputs the String string.
     * @syscap SystemCapability.Utils.Lang
     * @since 7
     */
    class TextEncoder {
        /**
         * Encoding format.
         * @since 7
         * @syscap SystemCapability.Utils.Lang
         */
        readonly encoding = "utf-8";
        /**
         * The textEncoder constructor.
         * @since 7
         * @syscap SystemCapability.Utils.Lang
         */
        constructor();
        /**
         * The textEncoder constructor.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         * @param encoding The string for encoding format.
         * @throws {BusinessError} 401 - The type of encoding must be string.
         */
        constructor(encoding?: string);
        /**
         * Returns the result of encoder.
         * @since 7
         * @deprecated since 9
         * @useinstead ohos.util.encodeInto
         * @syscap SystemCapability.Utils.Lang
         * @param input The string to be encoded.
         * @returns Returns the encoded text.
         */
        encode(input?: string): Uint8Array;
        /**
         * UTF-8 encodes the input string and returns a Uint8Array containing the encoded bytes.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         * @param input The string to be encoded.
         * @returns Returns the encoded text.
         * @throws {BusinessError} 401 - The type of input must be string.
         */
        encodeInto(input?: string): Uint8Array;
        /**
         * Encode string, write the result to dest array.
         * @since 7
         * @deprecated since 9
         * @useinstead ohos.util.encodeIntoUint8Array
         * @syscap SystemCapability.Utils.Lang
         * @param input The string to be encoded.
         * @param dest Decoded numbers in accordance with the format
         * @returns Returns Returns the object, where read represents
         * the number of characters that have been encoded, and written
         * represents the number of bytes occupied by the encoded characters.
         */
        encodeInto(input: string, dest: Uint8Array): {
            read: number;
            written: number;
        };
        /**
         * Encode string, write the result to dest array.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         * @param input The string to be encoded.
         * @param dest Decoded numbers in accordance with the format
         * @returns Returns Returns the object, where read represents
         * the number of characters that have been encoded, and written
         * represents the number of bytes occupied by the encoded characters.
         * @throws {BusinessError} 401 - if the input parameters are invalid.
         */
        encodeIntoUint8Array(input: string, dest: Uint8Array): {
            read: number;
            written: number;
        };
    }

TextDecoder源码(部分API在since 9 已废弃):

/**
     * The TextEncoder represents a text encoder that accepts a string as input,
     * encodes it in UTF-8 format, and outputs UTF-8 byte stream.
     * @syscap SystemCapability.Utils.Lang
     * @since 7
     */
    class TextDecoder {
        /**
         * The source encoding's name, lowercased.
         * @since 7
         * @syscap SystemCapability.Utils.Lang
         */
        readonly encoding: string;
        /**
         * Returns `true` if error mode is "fatal", and `false` otherwise.
         * @since 7
         * @syscap SystemCapability.Utils.Lang
         */
        readonly fatal: boolean;
        /**
         * Returns `true` if ignore BOM flag is set, and `false` otherwise.
         * @since 7
         * @syscap SystemCapability.Utils.Lang
         */
        readonly ignoreBOM = false;
        /**
         * The textEncoder constructor.
         * @since 7
         * @deprecated since 9
         * @useinstead ohos.util.TextDecoder.create
         * @syscap SystemCapability.Utils.Lang
         * @param encoding Decoding format
         */
        constructor(encoding?: string, options?: {
            fatal?: boolean;
            ignoreBOM?: boolean;
        });
        /**
         * The textEncoder constructor.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         */
        constructor();
        /**
         * Replaces the original constructor to process arguments and return a textDecoder object.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         * @param encoding Decoding format
         * @throws {BusinessError} 401 - if the input parameters are invalid.
         */
        static create(encoding?: string, options?: {
            fatal?: boolean;
            ignoreBOM?: boolean;
        }): TextDecoder;
        /**
         * Returns the result of running encoding's decoder.
         * @since 7
         * @deprecated since 9
         * @useinstead ohos.util.decodeWithStream
         * @syscap SystemCapability.Utils.Lang
         * @param input Decoded numbers in accordance with the format
         * @returns Return decoded text
         */
        decode(input: Uint8Array, options?: {
            stream?: false;
        }): string;
        /**
         * Decodes the input and returns a string. If options.stream is true, any incomplete byte sequences occurring
         * at the end of the input are buffered internally and emitted after the next call to textDecoder.decode().
         * If textDecoder.fatal is true, decoding errors that occur will result in a TypeError being thrown.
         * @since 9
         * @syscap SystemCapability.Utils.Lang
         * @param input Decoded numbers in accordance with the format
         * @returns Return decoded text
         * @throws {BusinessError} 401 - if the input parameters are invalid.
         */
        decodeWithStream(input: Uint8Array, options?: {
            stream?: boolean;
        }): string;
    }

审核编辑 黄宇

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分