<acronym id="s8ci2"><small id="s8ci2"></small></acronym>
<rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
<acronym id="s8ci2"></acronym>
<acronym id="s8ci2"><center id="s8ci2"></center></acronym>
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 = ???o????o??
└────────────────────────────────────────────────────────

剛開始在編碼的時候就已經出問題了,使用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

    文章

    586

    瀏覽量

    28683
  • Base64
    +關注

    關注

    0

    文章

    14

    瀏覽量

    8783
  • 鴻蒙OS
    +關注

    關注

    0

    文章

    189

    瀏覽量

    4304
收藏 人收藏

    評論

    相關推薦

    鴻蒙原生應用元服務開發-設備管理USB服務開發步驟

    == 0x80);dataUint8Array是要讀取的數據,類型為Uint8Array。 */ let inEndpoint : USBEndpoint = interface1.endpoints
    發表于 06-06 15:50

    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

    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 ?1835次閱讀

    UTF8String是如何編碼的?

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

    bigdecimal轉string類型

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

    嵌入式開發C語言中的uint8_t科普

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

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

    RSA加解密開始構建工具類就是舉步維艱,官方文檔雖然很全,但是還是有很多小瑕疵,在自己經過幾天的時間,徹底解決了中文亂碼的問題、分段加密的問題。
    的頭像 發表于 03-27 21:23 ?735次閱讀
    <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 ?344次閱讀
    <b class='flag-5'>鴻蒙</b>TypeScript學習第10天:【<b class='flag-5'>String</b>(字符串)】
    亚洲欧美日韩精品久久_久久精品AⅤ无码中文_日本中文字幕有码在线播放_亚洲视频高清不卡在线观看
    <acronym id="s8ci2"><small id="s8ci2"></small></acronym>
    <rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
    <acronym id="s8ci2"></acronym>
    <acronym id="s8ci2"><center id="s8ci2"></center></acronym>