0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

鴻蒙OS開發(fā)問題:(ArkTS) 【解決中文亂碼 string2Uint8Array、uint8Array2String】

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-03-27 21:38 ? 次閱讀

在進(jìn)行base64編碼中,遇到中文如果不進(jìn)行處理一定會出現(xiàn)亂碼

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);復(fù)制

輸出結(jié)果:

┌────────────────────────────────────────────────────────
 ├1 result1 = 5LiA5LqM5LiJ5Zub5LqU5YWt5LiD5YWr5Lmd5Y2BMTIz
└────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────
├1 result2 = ???o????o??
└────────────────────────────────────────────────────────

剛開始在編碼的時候就已經(jīng)出問題了,使用CryptoJS 框架 截止發(fā)稿前就一直存在這個問題,后面只有自己手?jǐn)]工具類:

import util from '@ohos.util';

class StringUtils {
  /**
   * string轉(zhuǎn)Uint8Array
   * @param value
   * @returns
   */
  string2Uint8Array1(value: string): Uint8Array {
    if (!value) return null;
    //
    let textEncoder = new util.TextEncoder();
    //獲取點流并發(fā)出 UTF-8 字節(jié)流 TextEncoder 的所有實例僅支持 UTF-8 編碼
    return textEncoder.encodeInto(value)
  }
  /**
   * string轉(zhuǎn)Uint8Array
   * @param value 包含要編碼的文本的源字符串
   * @param dest 存儲編碼結(jié)果的Uint8Array對象實例
   * @returns 它返回一個包含讀取和寫入的兩個屬性的對象
   */
  string2Uint8Array2(value: string, dest: Uint8Array) {
    if (!value) return null;
    if (!dest) dest = new Uint8Array(value.length);
    let textEncoder = new util.TextEncoder();
    //read:它是一個數(shù)值,指定轉(zhuǎn)換為 UTF-8 的字符串字符數(shù)。如果 uint8Array 沒有足夠的空間,這可能小于 src.length(length of source 字符串)。
    //dest:也是一個數(shù)值,指定存儲在目標(biāo) Uint8Array 對象 Array 中的 UTF-8 unicode 的數(shù)量。它總是等于閱讀。
    textEncoder.encodeIntoUint8Array(value, dest)
    // let result = textEncoder.encodeIntoUint8Array(value, dest)
    // result.read
    // result.written
  }
  /**
   * Uint8Array 轉(zhuǎn)  String
   * @param input
   */
  uint8Array2String(input: Uint8Array) {
    let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
    return textDecoder.decodeWithStream(input, { stream: false });
  }
  /**
   * ArrayBuffer 轉(zhuǎn)  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識別開發(fā)者項目中選擇的設(shè)備形態(tài),找到該設(shè)備的支持能力集,篩選支持能力集包含的API并提供API聯(lián)想"

  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));復(fù)制
鴻蒙OS開發(fā)更多內(nèi)容↓點擊HarmonyOSOpenHarmony技術(shù)
鴻蒙技術(shù)文檔開發(fā)知識更新庫gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在這。或+mau123789學(xué)習(xí),是v喔

搜狗高速瀏覽器截圖20240326151547.png

運行結(jié)果:

?

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

審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 源碼
    +關(guān)注

    關(guān)注

    8

    文章

    630

    瀏覽量

    29074
  • Base64
    +關(guān)注

    關(guān)注

    0

    文章

    14

    瀏覽量

    8795
  • 鴻蒙OS
    +關(guān)注

    關(guān)注

    0

    文章

    188

    瀏覽量

    4346
收藏 人收藏

    評論

    相關(guān)推薦

    鴻蒙OS開發(fā)實戰(zhàn):【ArkTS 實現(xiàn)MQTT協(xié)議(2)】

    1. 協(xié)議傳輸通道僅為TCPSocket 2. 基于HarmonyOS SDK API 9開發(fā) 3. 開發(fā)語言:ArkTS,TypeScript
    的頭像 發(fā)表于 04-01 14:48 ?1348次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>OS</b><b class='flag-5'>開發(fā)</b>實戰(zhàn):【<b class='flag-5'>ArkTS</b> 實現(xiàn)MQTT協(xié)議(<b class='flag-5'>2</b>)】

    HarmonyOS Next原生應(yīng)用開發(fā)-從TS到ArkTS的適配規(guī)則(七)

    this.firstName + \' \' + this.lastName; } } ArkTS class Person { protected ssn: string private firstName
    發(fā)表于 07-22 15:11

    HarmonyOS Next原生應(yīng)用開發(fā)-從TS到ArkTS的適配規(guī)則(八)

    interface I { new (s: string): I } function fn(i: I) { return new i(\'hello\'); } ArkTS interface I
    發(fā)表于 07-23 16:54

    Wiley - 《Array and Phased Array Antenna Basics》

     Wiley - 《Array and Phased Array Antenna Basics》 1Radiation2Antennas 
    發(fā)表于 06-16 17:34

    菜鳥求助:如何將一個uint32_t保留低8位變成一個uint8_t?

    比如 :uint32_t data1;,uint8_t??data2;data2 = data1;是不是就將最低的8位傳送給了 data
    發(fā)表于 04-08 13:29

    LabVIEW動態(tài)鏈接庫參數(shù)匹配問題

    shortU16cmplx64CSGcmplx128CDBcmplxExtCXTCStrStringfloat32SGLfloat64DBLfloatExtEXTint8I8int16I16int32I32LStrHandleStringLVBooleanBooleanuInt8U8uInt16U16uInt32
    發(fā)表于 05-14 09:40

    一文區(qū)分Array與Vec的使用場景

    ,其實現(xiàn)意圖是通過map從每個Mem中讀出指定地址的數(shù)據(jù),得到一個Array[UInt]數(shù)組,而隨后之所以調(diào)用toSeq在于我們從Array[UInt]中選擇所使用的索引類型是
    發(fā)表于 06-28 15:30

    請問uint8 HalLedSet (uint8 leds, uint8 mode)這個函數(shù)怎么使用?

    沒明白uint8 HalLedSet (uint8 leds, uint8 mode)這個函數(shù)怎么使用?例如我LED的控制GPIO是A15,#define LED_PIN (GPIO_Pin_15
    發(fā)表于 08-19 06:23

    鴻蒙 OS 應(yīng)用開發(fā)初體驗

    的 IDE、鴻蒙生態(tài)的開發(fā)語言 ArkTS,通過模擬器運行起來了鴻蒙 OS 版 HelloWorld。對于已經(jīng)有移動
    發(fā)表于 11-02 19:38

    如何使用C語言實現(xiàn)動態(tài)擴(kuò)容的string

    眾所周知,C++ 中的string使用比較方便,關(guān)于C++ 中的string源碼實現(xiàn)可以看我的這篇文章:源碼分析C++的string的實現(xiàn)
    的頭像 發(fā)表于 10-25 10:59 ?1968次閱讀

    單片機(jī)常用死機(jī)寫法總結(jié)

    array[10]; test_point = array;//錯誤舉例2 char test_string[8]; sprintf(te
    發(fā)表于 01-13 15:04 ?3次下載
    單片機(jī)常用死機(jī)寫法總結(jié)

    UTF8String是如何編碼的?

    UniversalString和UTF8String 都支持完全相同的字符集,前64K 字符都是BMPString 中的字符集。請注意,BMPString 的前128 個字符與IA5String
    的頭像 發(fā)表于 08-26 09:55 ?2000次閱讀
    UTF<b class='flag-5'>8String</b>是如何編碼的?

    bigdecimal轉(zhuǎn)string類型

    將BigDecimal轉(zhuǎn)換為String類型是在Java編程中常常遇到的一個問題。BigDecimal是Java中用于表示高精度十進(jìn)制數(shù)的類,而String則是用于表示文本字符串的數(shù)據(jù)類型。在某些
    的頭像 發(fā)表于 11-30 11:09 ?5992次閱讀

    嵌入式開發(fā)C語言中的uint8_t科普

    在嵌入式開發(fā)中的C語言代碼中,經(jīng)??梢钥吹筋愃?b class='flag-5'>uint8_t、uint16_t、uint32_t、uint64_t這種數(shù)據(jù)類型,在教材中卻從
    的頭像 發(fā)表于 12-13 16:30 ?5898次閱讀
    嵌入式<b class='flag-5'>開發(fā)</b>C語言中的<b class='flag-5'>uint8</b>_t科普

    鴻蒙OS開發(fā)問題:(ArkTS)【 RSA加解密,解決中文亂碼等現(xiàn)象】

    RSA加解密開始構(gòu)建工具類就是舉步維艱,官方文檔雖然很全,但是還是有很多小瑕疵,在自己經(jīng)過幾天的時間,徹底解決了中文亂碼的問題、分段加密的問題。
    的頭像 發(fā)表于 03-27 21:23 ?1578次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>OS</b><b class='flag-5'>開發(fā)問</b>題:(<b class='flag-5'>ArkTS</b>)【 RSA加解密,解決<b class='flag-5'>中文</b><b class='flag-5'>亂碼</b>等現(xiàn)象】