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. matplotlib学习日记(十)-共享绘图区域的坐标轴

    (1)共享单一绘图区域的坐标轴 ''' 上一讲介绍了画布的划分,有时候想将多张图放在同一个绘图区域, 不想在每个绘图区域只绘制一幅图形,这时候借助共享坐标轴的方法实现在一个绘图区 绘制多幅图形的目的. ...

  2. .net core 和 WPF 开发升讯威在线客服与营销系统:系统总体架构

    本系列文章详细介绍使用 .net core 和 WPF 开发 升讯威在线客服与营销系统 的过程.本产品已经成熟稳定并投入商用. 在线演示环境:https://kf.shengxunwei.com 注意 ...

  3. springcloud根据日期区间查询同时其他字段模糊查询

    /** * 分页查询完工送检单 * @param entity * @param query * @return */ @GetMapping("getQcProInsAppOverList ...

  4. [leetcode]720. Longest Word in Dictionary字典中最长的单词

    b.compareTo(a) 这个函数是比较两个值得大小,如果b比a大,那么返回1 如果小,那么返回-1,相等返回0 如果比较的是字符串,那么比较字典编纂顺序,b靠前返回-1,靠后返回1 这个题的核心 ...

  5. 在 ASP.NET Core和Worker Service中使用Quartz.Net

    现在有了一个官方包Quartz.Extensions.Hosting实现使用Quartz.Net运行后台任务,所以把Quartz.Net添加到ASP.NET Core或Worker Service要简 ...

  6. Java学习日报7.25

    package shui; public class Shui { public static void main(String[] args) { // TODO 自动生成的方法存根 int g,s ...

  7. 【转载】VUE的背景图引入

    我现在的项目要将登录页面的背景引一图片做为背景图片,按原jsp中的写法,发现无法找到背景图片,最后从网上查资料,采用上面的写法,成功显示出背景图片,参考网址 https://blog.csdn.net ...

  8. 微信小程序 - bilibili模仿

    今天真是个大坑,onLoad => 写成了OnLoad 程序一直没法执行, 晚上下班的时候,在微信的小程序中,this不可以直接访问data中的值,得this.data才能访问..

  9. DRF之访问权限控制和访问频率控制(节流)

    权限控制 前言 用户验证用户权限,根据不同访问权限控制对不同内容的访问. 建议了解视图.token验证的内容. 使用流程 自定义访问权限类,继承BasePermission,重写has_permiss ...

  10. 一文详解 ARP 协议

    我把自己以往的文章汇总成为了 Github ,欢迎各位大佬 star https://github.com/crisxuan/bestJavaer 公众号连载计算机网络文章如下 ARP,这个隐匿在计网 ...