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 ...
随机推荐
- 使用NPOI读取Word文档内容并进行修改
前言 网上使用NPOI读取Word文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的. 参考博文 http://www.cnblogs.com/mahongbiao/p/376 ...
- (三)文件的链接(ln)
一.链接的分类及特点 当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在某个固定的目录,放上该文件,然后在 其它的目录下用ln命令链接(link ...
- Netty源码解析 -- PoolChunk实现原理(jemalloc 3的算法)
前面文章已经分享了Netty如何实现jemalloc 4算法管理内存. 本文主要分享Netty 4.1.52之前版本中,PoolChunk如何使用jemalloc 3算法管理内存. 感兴趣的同学可以对 ...
- element-ui 表单 v-if 不能验证问题
element-ui 表单v-if 很多人会遇到无法验证的问题,网上很多是在el-form-item标签前加一个div然后把v-if拿到div上去像这样 <div v-if="addc ...
- linux 下socket编程
原理 类unix系统中, 一切皆文件, 诸如磁盘文件, 显卡, 内核驱动, 网络协议栈等 socket就是linux中提供的用于网络通信的文件接口, 两台机器之间可以读写消息 在使用socket真正的 ...
- Logstash学习之路(三)Logstash处理时区、类型转换、删除字段的案例配置
#输入 input { file { path => ["文件路径"] #自定义类型 type => "自定义" start_position =& ...
- Linux 下挂载新硬盘方法(转)
1.关闭服务器加上新硬盘 2.启动服务器,以root用户登录 3.查看硬盘信息 #fdisk -l Disk /dev/sda: 42.9 GB, 42949672960 bytes 255 ...
- 「珍贵历史资料鉴赏」CF786B 题解
写在前面 偶然翻到一篇 2019-08-07 18:58 写的未发布的题解. 给大家找点乐子玩. 正文 知识点:线段树优化建图 线段树优化建图 用于解决 类似 从 x 向区间[L,R]的 区间连边问题 ...
- Linux服务器初始化调优及安全加固
一,开启iptables 仅开放必要的SSH端口和监控端口 示例:SSH tcp 22snmpd udp 161nrpe tcp 5666本人公网IP全端口开放 二,除非特别熟悉selinux配置,否 ...
- 【C++】《C++ Primer 》第十四章
第十四章 重载运算与类型转换 一.基本概念 重载运算符是具有特殊名字的函数:由关键字operator和其后要定义的运算符号共同组成.也包含返回类型.参数列表以及函数体. 当一个重载的运算符是成员函数时 ...