99精品伊人亚洲|最近国产中文炮友|九草在线视频支援|AV网站大全最新|美女黄片免费观看|国产精品资源视频|精彩无码视频一区|91大神在线后入|伊人终合在线播放|久草综合久久中文

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

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

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

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

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-03-27 21:38 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

在進行base64編碼中,遇到中文如果不進行處理一定會出現(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);復制

輸出結(jié)果:

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

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

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ù)值,指定存儲在目標 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ā)者項目中選擇的設備形態(tài),找到該設備的支持能力集,篩選支持能力集包含的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));復制
鴻蒙OS開發(fā)更多內(nèi)容↓點擊HarmonyOSOpenHarmony技術
鴻蒙技術文檔開發(fā)知識更新庫gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在這。或+mau123789學習,是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)站授權轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 源碼
    +關注

    關注

    8

    文章

    671

    瀏覽量

    30345
  • Base64
    +關注

    關注

    0

    文章

    26

    瀏覽量

    9046
  • 鴻蒙OS
    +關注

    關注

    0

    文章

    191

    瀏覽量

    4997
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關推薦
    熱點推薦

    鴻蒙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 ?2179次閱讀
    <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原生應用開發(fā)-從TS到ArkTS的適配規(guī)則(七)

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

    HarmonyOS Next原生應用開發(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

    【HarmonyOS NEXT】關鍵資產(chǎn)存儲開發(fā)案例

    , this.string2Array(value)); // 關鍵資產(chǎn)明文。 // 類型為Uint8Array,長度為1-1024字節(jié) attr.set(asset.Tag.ALIAS
    發(fā)表于 05-16 16:21

    ArkUI-X平臺橋接Bridge說明

    為例,ArkTS和Java沒有相互調(diào)用的能力,為了實現(xiàn)ArkTS和Java交互,需要ArkTS與C++交互,C++再與Java交互,反之亦然。但是對于開發(fā)者,就像是
    發(fā)表于 06-19 23:12

    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

    請問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

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

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

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

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

    UTF8String是如何編碼的?

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

    bigdecimal轉(zhuǎn)string類型

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

    嵌入式開發(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 ?8906次閱讀
    嵌入式<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 ?2405次閱讀
    <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)象】