【ReactNative/JS】uint8array转string convert uint8array to string

2023-11-05

客户端/服务器使用的protobuffer交互,客户端收到的是uint8array,面临着从unit8array转string,我使用的是下面的Crossplatform method


Working with node.js or other javascript platforms (multioperability), you'll find that some methods decide to return something different than a string. An Uint8Array is a typed array that represents an array of 8-bit unsigned integers.

The following list of methods , provide a collection of efficient ways to convert an Uint8Array to a regular string in javascript.

Little strings

The following method is acceptable for little arrays (>=100k characters), otherwise you'll get exceptions as RangeError : Maximum call stack size exceeded or Out of stack space. However you need to know that this method doesn't play good with UTF-8 characters.

function uint8arrayToStringMethod(myUint8Arr){
   return String.fromCharCode.apply(null, myUint8Arr);
}

Browser implementation

If your javascript is being executed in a browser, you can make use of the TextEncoder and TextDecoder native functions which allow you to choose which codification you want to use. The Encoding API helps solving the string conversion problem.

/**
 * Convert an Uint8Array into a string.
 *
 * @returns {String}
 */
function Decodeuint8arr(uint8array){
    return new TextDecoder("utf-8").decode(uint8array);
}

/**
 * Convert a string into a Uint8Array.
 *
 * @returns {Uint8Array}
 */
function Encodeuint8arr(myString){
    return new TextEncoder("utf-8").encode(myString);
}

Crossplatform method

The following method is very useful and works pretty good. It doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments. Works through the UTF-8 convention.

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

Large blocks

If your data block is huge, you may want to use a method that works properly with huge data (an async method). In this case we'll create blob that contains our Uint8Array and then we'll use the file reader to read it as text.

/**
 * Converts an array buffer to a string
 *
 * @param {Uin8} uint8arr | The buffer to convert
 * @param {Function} callback | The function to call when conversion is complete
 */
function largeuint8ArrToString(uint8arr, callback) {
    var bb = new Blob([uint8arr]);
    var f = new FileReader();
    f.onload = function(e) {
        callback(e.target.result);
    };http://ourcodeworld.com/articles/read/164/how-to-convert-an-uint8array-to-string-in-javascript
    
    f.readAsText(bb);
}

// Usage example
// "Hello" in Uint8Array format
var myuint8Arr = new Uint8Array([72, 101, 108, 108, 111, 32, 33]);

largeuint8ArrToString(myuint8Arr,function(text){
    // Hello
    console.log(text);
});

Note: as said before, this method is recommendable only if you handle huge datasets.

Have fun 


原文连接:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【ReactNative/JS】uint8array转string convert uint8array to string 的相关文章

随机推荐

  • 自动驾驶和自然语言如何结合?NuPrompt来了!

    点击下方卡片 关注 自动驾驶之心 公众号 ADAS巨卷干货 即可获取 gt gt 点击进入 自动驾驶之心 大模型 技术交流群 自动驾驶语言提示 原标题 Language Prompt for Autonomous Driving 论文链接
  • VMware Workstation17下载安装、环境搭建、网络配置最小化安装操作步骤

    一 VMware Workstation17下载安装 1 官网下载 官网网址 https www vmware com cn products workstation pro html 安装Workstation 17 Pro for Wi
  • openssl+http实现https

    openssl详解及实现https openssl详解及实现https OpenSSL 是一个安全套接字层密码库 囊括主要的密码算法 常用的密钥和证书封装管理功能及SSL协议 并提供丰富的应用程序供测试或其它目的使用 秘钥算法和协议 对称加
  • 数据库基础--多表查询

    在数据库查询过程中无法避免的需要从两张表中同时查询数据 此时我们需要用到各式各样的多表查询方式 接下来 简单介绍一下数据库基础的多表查询方式 以便于让大家更好的了解多表查询的过程 多表查询 项目开发中 在进行数据库表结构设计时 会根据业务需
  • 【五一创作】iSH修改hostname(主机名)【美化】【短篇技术类文章】

    最后一次更新 2023 4 30 请勿利用文章内的相关技术从事非法测试 由于传播 利用此文所提供的信息而造成的任何直接或者间接的后果及损失 均由使用者本人负责 作者不为此承担任何责任 文章目录 1 前言 简单 的介绍 2 踩坑 摸索 3 解
  • Arduin调节舵机的思路

    一 先判断舵机能够调节的最大值和最小值 二 让舵机转动能够平滑 三 用二维数组和for循环实现码垛机器人的效果 四 机械臂在指令模式的基础上增加手柄模式 手柄模式可以 通过键盘上字符按键操控舵机机械臂 五 通过蓝牙模块进行蓝牙无线设备连接
  • Python读取mat文件-转csv文件

    这篇教程主要介绍如何使用Python读取mat文件并且转csv文件 一 读取mat文件和转CSV 首先将MATLAB生成的mat文件存储在一个目录下 import pandas as pd import scipy from scipy i
  • 王者荣耀服务器维护七月,《王者荣耀》7.28不停服维护更新攻略教程 7月28日更新公告...

    在王者荣耀的游戏中 7月28日进行了不停服的更新维护 此次更新除了常规的修复以外 还带来了蔷薇珍宝阁活动 接下来就让小编带大家一起来看看详细的内容吧 王者荣耀2021年7月28日全服不停机更新公告 更新时间 7月28日8 30 9 30 更
  • RL 暂态电路与磁能

    前言 RL 电路是一个电阻 R 和 自感线圈 L 组成的 RL 电路 在连接或者接通电源U 的时候 由于自感电动势的作用 电路中的电流不会瞬间改变 而是一个连续的渐变的过程 通常这个时间很短暂 所以被称为暂态过程 正文 看看书上是怎么写的
  • 【iOS】—— APP启动流程

    文章目录 APP启动流程 冷启动和热启动 APP完整的启动流程 1 main函数执行前 系统会做的事 2 main函数执行后 3 首屏渲染完成后 Mach O APP启动流程 冷启动和热启动 冷启动 启动时 App的进程不在系统里 需要开启
  • CSS设置字间距、行间距、首行缩进

    CSS设置字间距 行间距 首行缩进 ps 本人亲测 阿里云2核4G5M的服务器性价比很高 新用户一块多一天 老用户三块多一天 最高可以买三年 感兴趣的可以戳一下 阿里云折扣服务器 字间距 1 text indent设置抬头距离css缩进 即
  • 大数据时代,区块链在数据安全领域有什么样的表现?

    大数据时代之下 一如我们无法抗拒科技进步带来的便捷及欢愉 我们同样也无法避免在享受这一切的过程中留下自己的 数字足迹 正因如此 数据如今已然被纳入企业的战略资源 开始指导决策 成为其提高行业核心竞争力的关键一环 当今的数字化时代 数据可谓是
  • ubuntu18.04安装GPU PyTorch

    转载自这篇文章 安装GPU版本的PyTorch 这里选择用pip进行安装 首先需要安装pip 执行命令sudo apt intall python pip3 该步骤可以跳过 现在建议配置pip虚拟环境 为此我们需要配置virtualenv
  • 一、用 ChatGPT 充当面试官

    目录 一 如何让 ChatGPT 充当面试官 1 1正确使用 1 2 反例 二 模拟面试 2 1 ChatGPT 让我介绍自己 2 2 ChatGPT 提问技术问题 2 2 1 技术问题 2 2 2 下一个问题
  • wifi名称可以有空格吗_但是名称中不能有空格

    Excel表格的每一个单元格都有一个默认的名称 其命名规则是列标加横标 例如A1表示第一列 第一行的单元格 如果要将某单元格重新命名 可以运用以下两种方法 工具 原料 Microsoft Office WPS Office 方法一 1 打开
  • [305]mysql1062错误:Duplicate entry '...' for key 'PRIMARY

    问题解释 Duplicate entry for key PRIMARY 即插入数据时 要插入数据的主键数据 已经存在 不能再重复添加了 例 Duplicate entry 0 for key PRIMARY是指主键为0的数据已经存在 不能
  • Linux常用命令大全(非常全!!!)

    前言 本文特点 授之以渔 了解命令学习方法 用途 不再死记硬背 拒绝漫无目的 准确无误 所有命令执行通过 环境为centos7 拒绝复制粘贴 实用性高 命令多为实际工作中用到的 实例讲解 拒绝纯理论 条理清晰 分类归纳 快速找到想要的命令
  • java疯狂讲义 笔记_《疯狂Java讲义》阅读笔记1

    2 2 UML统一建模语言 从粗粒度到细粒度 最常用的UML图 部署图 从物理处理器和设备的角度画图 其中一个设备中可能包括零个或若干个组件 用例图 表示的是一系列功能 一个用例表示系统的一个功能模块 如登录模块 组件图 多个类共同组成的j
  • OpenGL学习笔记(2)第一个程序——犹他茶壶(Teapot)

    好了 python opengl的开发环境搭建好后 我们就可以开始学习了 这里 我们先学习一个常见的例子 犹他茶壶 先贴代码 from OpenGL GL import from OpenGL GLU import from OpenGL
  • 【ReactNative/JS】uint8array转string convert uint8array to string

    客户端 服务器使用的protobuffer交互 客户端收到的是uint8array 面临着从unit8array转string 我使用的是下面的Crossplatform method Working with node js or oth