https://github.com/mdn/dom-examples/blob/master/web-crypto/import-key/spki.js

How to convert ArrayBuffer to and from String  |  Web https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

ArrayBuffers are used to transport raw data and several new APIs rely on them, including WebSocketsWeb Intents 2](https://www.html5rocks.com/en/tutorials/file/xhr2/) and WebWorkers. However, because they recently landed in the JavaScript world, sometimes they are misinterpreted or misused.

Semantically, an ArrayBuffer is simply an array of bytes viewed through a specific mask. This mask, an instance ofArrayBufferView, defines how bytes are aligned to match the expected structure of the content. For example, if you know that the bytes in an ArrayBuffer represent an array of 16-bit unsigned integers, you just wrap the ArrayBuffer in a Uint16Array view and you can manipulate its elements using the brackets syntax as if the Uint16Array was an integer array:

// suppose buf contains the bytes [0x02, 0x01, 0x03, 0x07]
// notice the multibyte values respect the hardware endianess, which is little-endian in x86
var bufView = new Uint16Array(buf);
if (bufView[0]===258) {   // 258 === 0x0102
  console.log("ok");
}
bufView[0] = 255;    // buf now contains the bytes [0xFF, 0x00, 0x03, 0x07]
bufView[0] = 0xff05; // buf now contains the bytes [0x05, 0xFF, 0x03, 0x07]
bufView[1] = 0x0210; // buf now contains the bytes [0x05, 0xFF, 0x10, 0x02]
 

One common practical question about ArrayBuffer is how to convert a String to an ArrayBuffer and vice-versa. Since an ArrayBuffer is, in fact, a byte array, this conversion requires that both ends agree on how to represent the characters in the String as bytes. You probably have seen this "agreement" before: it is the String's character encoding (and the usual "agreement terms" are, for example, Unicode UTF-16 and iso8859-1). Thus, supposing you and the other party have agreed on the UTF-16 encoding, the conversion code could be something like:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
 

Note the use of Uint16Array. This is an ArrayBuffer view that aligns bytes of the ArrayBuffers as 16-bit elements. It doesn't handle the character encoding itself, which is handled as Unicode by String.fromCharCode andstr.charCodeAt.

Note: A robust implementation of the String to ArrayBuffer conversion capable of handling more encodings is provided by the stringencoding library. But, for simple usage where you control both sides of the communication pipe, the code above is probably enough. A standardized API specification for String encoding is being drafted by the WHATWG working group.

A popular StackOverflow question about this has a highly voted answer with a somewhat convoluted solution to the conversion: create a FileReader to act as a converter and feed a Blob containing the String into it. Although this method works, it has poor readability and I suspect it is slow. Since unfounded suspicions have driven many mistakes in the history of humanity, let's take a more scientific approach here. I have jsperf'ed the two methods and the result confirms my suspicion and you check out the demo here.

In Chrome 20, it is almost 27 times faster to use the direct ArrayBuffer manipulation code on this article than it is to use the FileReader/Blob method.

Convert a string into an ArrayBuffer的更多相关文章

  1. Convert.ToInt32(string '000000003') 变成了 3

    Convert.ToInt32(string '000000003') 变成了 3 但是在查询的时候需要用的是string 这里的convert.toint32 反而起了坏作用,不是所有的时候都要用c ...

  2. convert \uXXXX String to Unicode Characters in Python3.x

    转换\uXXXX if Python3.x: str.decode no longer exists in 3.x. that']s why Python 3.4: str : AttributeEr ...

  3. . ToString(),Convert.ToString(),(string),as比较:

    http://www.cnblogs.com/chehaoj/archive/2010/02/23/1671955.html 通常 object 到 string 有四种方式(假设有object ob ...

  4. Convert DataFrame string complex i to j python // “Cloning” row or column vectors

    https://stackoverflow.com/questions/30808286/convert-dataframe-string-complex-i-to-j-python https:// ...

  5. csharp: Double Convert To String

    /// <summary> /// /// </summary> /// <param name="fl"></param> /// ...

  6. How to: Convert Between Various String Types

      This topic demonstrates how to convert various Visual C++ string types into other strings. The str ...

  7. Java Convert String & Int

    To convert a int to string: int num = 123; String str = String.valueOf(num); To convert a string to ...

  8. Convert a byte[] array to readable string format. This makes the "hex" readable!

    /* * Java Bittorrent API as its name indicates is a JAVA API that implements the Bittorrent Protocol ...

  9. How to convert String to Date – Java

    In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners ar ...

随机推荐

  1. IIS重写2.0 IIS伪静态 下载地址

    IIS重写2.0 IIS伪静态 下载地址 https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads Downloa ...

  2. MySQL忘记密码了怎么解决

    前言:在不考虑到原来用户对关联数据库的授权问题的情况下,有以下三种思路解决 #1.登录状态下修改 说明:在登录状态的话,直接使用命令修改密码就行了 mysql> use mysql; mysql ...

  3. 在 xunit 测试项目中使用依赖注入

    在 xunit 测试项目中使用依赖注入 Intro 之前写过几篇 xunit 依赖注入的文章,今天这篇文章将结合我在 .NET Conf 上的分享,更加系统的分享一下在测试中的应用案例. 之所以想分享 ...

  4. bean中属性名和json不一致解决方案(请求和响应)

    此时@RequestBody.@ResponseBody需要与@JsonProperty结合使用,才能做到请求正常解析,响应按要求格式返回. 注意@JsonProperty注解的位置需要加在gette ...

  5. 浅谈IAT加密原理及过程

    上一次做完代码段加密后,又接触到了新的加密方式:IAT加密 IAT加密是通过隐藏程序的导入表信息,以达到增加分析程序的难度.因为没有导入表,就无法单纯的从静态状态下分析调用了什么函数,动态调试时,也无 ...

  6. java 反射随记

    记录一下有关 Class 对象的相关方法: 1.获取 Class 对象的三个方法: ⑴ 使用 Class.forName("全限定类名") ,参数是该类的全限定类名,可拓展性强: ...

  7. 为什么import React from 'react',React首字母必须大写?

    很奇怪的是,明明没有用到 React,但是我不得不 import React.这是为什么? import React from 'react'; export default function (pr ...

  8. Linux操作系统的文件目录结构

    一 --- 导读 首先记住一句经典的话:"linux世界中,万事万物皆为文件" 二---linux的目录结构示意图和windows下的目录结构示意图(本图需要背诵) 三---各目录 ...

  9. 《深入理解Java虚拟机》 Java对象的生命周期

    Java虚拟机运行时数据区 方法区:存储 类信息.常量.静态变量.即使编译器编译后的代码等数据,也有别名叫做非堆.  方法区其中有包含有 运行时常量池,用于存放编译期生成的各种字面量和符号引用.其中, ...

  10. 【分享】wdcp服务器管理系统常用维护工具

    wdcp (WDlinux Control Panel) 是一套用PHP开发的Linux服务器管理系统,类似国外流行的cpanel,旨在易于使用和管理Linux服务器,可以在线通过网页管理服务器和虚拟 ...