0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

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

jf_46214456 来源:jf_46214456 作者:jf_46214456 2024-03-27 21:38 次阅读

在进行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开发更多内容↓点击HarmonyOSOpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。或+mau123789学习,是v喔

搜狗高速浏览器截图20240326151547.png

运行结果:

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;
    }

审核编辑 黄宇

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

    关注

    8

    文章

    573

    浏览量

    28585
  • Base64
    +关注

    关注

    0

    文章

    14

    浏览量

    8777
  • 鸿蒙OS
    +关注

    关注

    0

    文章

    130

    浏览量

    4279
收藏 人收藏

    评论

    相关推荐

    Wiley - 《Array and Phased Array Antenna Basics》

     Wiley - 《Array and Phased Array Antenna Basics》 1Radiation2Antennas 
    发表于 06-16 17:34

    菜鸟求助:如何将一个uint32_t保留低8位变成一个uint8_t?

    比如 :uint32_t data1;,uint8_t  data2;data2 = data1;是不是就将最低的8位传送给了 data
    发表于 04-08 13:29

    HalUARTWrite()函数输出 乱码显示

     LCD_WRITE_STRING_VALUE() 这个函数就能正常显示出数字来?什么原因? uint8 data[3]=[0];          data[0]=sec;          data[1]=min
    发表于 08-28 10:28

    STM8S105K4跟ES8323S的I2C通信,接收数据出现的错误

    最近在做STM8S105K4跟ES8323S的I2C通信遇到了一个问题。当我发送的数据在6个以内时,接收的数据全都正确,但是当6ODR |= (uint8_t)GPIO_Pin_SDA; //sda
    发表于 12-27 16:57

    LabVIEW动态链接库参数匹配问题

    shortU16cmplx64CSGcmplx128CDBcmplxExtCXTCStrStringfloat32SGLfloat64DBLfloatExtEXTint8I8int16I16int32I32LStrHandleStringLVBooleanBooleanuInt8U8uInt16U16uInt32
    发表于 05-14 09:40

    请问uint8 os_err和CPU_INT08U os_err的区别在哪里?

    问一个比较弱智的问题:uint8 os_err 和 CPU_INT08U os_err 的区别在哪里?出于神马考虑 要用 CPU_INT08U os_err 这样的语句 ?
    发表于 06-30 22:25

    一文区分Array与Vec的使用场景

    ,其实现意图是通过map从每个Mem中读出指定地址的数据,得到一个Array[UInt]数组,而随后之所以调用toSeq在于我们从Array[UInt]中选择所使用的索引类型是
    发表于 06-28 15:30

    请问uint8 HalLedSet (uint8 leds, uint8 mode)这个函数怎么使用?

    没明白uint8 HalLedSet (uint8 leds, uint8 mode)这个函数怎么使用?例如我LED的控制GPIO是A15,#define LED_PIN (GPIO_Pin_15
    发表于 08-19 06:23

    鸿蒙 OS 应用开发初体验

    的 IDE、鸿蒙生态的开发语言 ArkTS,通过模拟器运行起来了鸿蒙 OS 版 HelloWorld。对于已经有移动
    发表于 11-02 19:38

    如何使用C语言实现动态扩容的string

    众所周知,C++ 中的string使用比较方便,关于C++ 中的string源码实现可以看我的这篇文章:源码分析C++的string的实现
    的头像 发表于 10-25 10:59 1806次阅读

    UTF8String是如何编码的?

    UniversalString和UTF8String 都支持完全相同的字符集,前64K 字符都是BMPString 中的字符集。请注意,BMPString 的前128 个字符与IA5String
    的头像 发表于 08-26 09:55 1563次阅读
    UTF8<b class='flag-5'>String</b>是如何编码的?

    bigdecimal转string类型

    将BigDecimal转换为String类型是在Java编程中常常遇到的一个问题。BigDecimal是Java中用于表示高精度十进制数的类,而String则是用于表示文本字符串的数据类型。在某些
    的头像 发表于 11-30 11:09 3527次阅读

    嵌入式开发C语言中的uint8_t科普

    在嵌入式开发中的C语言代码中,经常可以看到类似uint8_t、uint16_t、uint32_t、uint64_t这种数据类型,在教材中却从
    的头像 发表于 12-13 16:30 1262次阅读
    嵌入式<b class='flag-5'>开发</b>C语言中的<b class='flag-5'>uint</b>8_t科普

    鸿蒙OS开发问题:(ArkTS)【 RSA加解密,解决中文乱码等现象】

    RSA加解密开始构建工具类就是举步维艰,官方文档虽然很全,但是还是有很多小瑕疵,在自己经过几天的时间,彻底解决了中文乱码的问题、分段加密的问题。
    的头像 发表于 03-27 21:23 347次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>OS</b><b class='flag-5'>开发问</b>题:(<b class='flag-5'>ArkTS</b>)【 RSA加解密,解决<b class='flag-5'>中文</b><b class='flag-5'>乱码</b>等现象】

    鸿蒙TypeScript学习第10天:【String(字符串)】

    String 对象用于处理文本(字符串)。
    的头像 发表于 04-08 14:32 219次阅读
    <b class='flag-5'>鸿蒙</b>TypeScript学习第10天:【<b class='flag-5'>String</b>(字符串)】