Convert a string into an ArrayBuffer
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 WebSockets, Web 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的更多相关文章
- Convert.ToInt32(string '000000003') 变成了 3
Convert.ToInt32(string '000000003') 变成了 3 但是在查询的时候需要用的是string 这里的convert.toint32 反而起了坏作用,不是所有的时候都要用c ...
- 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 ...
- . ToString(),Convert.ToString(),(string),as比较:
http://www.cnblogs.com/chehaoj/archive/2010/02/23/1671955.html 通常 object 到 string 有四种方式(假设有object ob ...
- 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:// ...
- csharp: Double Convert To String
/// <summary> /// /// </summary> /// <param name="fl"></param> /// ...
- How to: Convert Between Various String Types
This topic demonstrates how to convert various Visual C++ string types into other strings. The str ...
- Java Convert String & Int
To convert a int to string: int num = 123; String str = String.valueOf(num); To convert a string to ...
- 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 ...
- 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 ...
随机推荐
- 简单介绍下各种 JavaScript 解析器
作者:沧海 各种js解析器是前端工程化的基石,可以说如果没有它,很多工程化都无法正常执行,我们每天用到的babel.webpack.eslint.TypeScript背后都需要一套对应的js解析器,今 ...
- 面试官让你讲讲Linux内核的竞争与并发,你该如何回答?
@ 目录 内核中的并发和竞争简介 原子操作 原子操作简介 整型原子操作函数 位原子操作函数 原子操作例程 自旋锁 自旋锁简介 自旋锁操作函数 自旋锁例程 读写自旋锁 读写锁例程 顺序锁 顺序锁操作函数 ...
- js表单简单验证(手机号邮箱)
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncod ...
- Java学习日报7.17
控制台运行
- SSM框架整合模板
SSM框架整合--MAVEN依赖 spring方面(包含了springmvc): spring-webmvc:spring与mvc的整合依赖,主要包括spring的核心包和springmvc需要的包 ...
- vue项目中的路由守卫
路由守卫的意义就相当于一个保安一样,作用很大,在实际的项目中运用也是不少,也就是当客户在登陆自己账号的时候,有可能存在客户有啥事的时候,自己后台或者pc的关闭全部浏览器,没有点击退出登录,或者在退出登 ...
- SpringBoot 集成Elasticsearch进行简单增删改查
一.引入的pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...
- #3使用html+css+js制作网页 番外篇 制作接收php
使用html+css+js制作网页 番外篇 制作接收php 本系列链接 基础 php语法 例子 本系列链接 #1使用html+css+js制作网站教程 准备 #2使用html+css+js制作网站教程 ...
- UnityToLaya小插件-找出空格并替换
unity导出的文件中经常会出现带有空格的节点或者文件夹 而这些空格在本地开发测试过程中不会出现,当这些带有空格路径的文件需要放到网络上时,就出现问题了 所以这里写了一个简单的查找并清理空格的插件, ...
- 【Spring】Spring 事务控制
Spring 事务控制 Spring 事务控制介绍 JavaEE 体系进行分层开发,事务控制位于业务层,Spring 提供了分层设计业务层的事务处理解决方案. Spring 的事务控制都是基于 AOP ...