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 ...
随机推荐
- matplotlib学习日记(十一)---坐标轴高阶应用
(一)设置坐标轴的位置和展示形式 (1)向画布中任意位置添加任意数量的坐标轴 ''' 通过在画布的任意位置和区域,讲解设置坐标轴的位置和坐标轴的展示形式的实现方法, 与subplot,subplots ...
- [leetcode]205. Isomorphic Strings同构字符串
哈希表可以用ASCII码数组来实现,可以更快 public boolean isIsomorphic(String s, String t) { /* 思路是记录下每个字符出现的位置,当有重复时,检查 ...
- device_create为何可以在/sys/class/具体类/属性文件?怎么实现的
答案: 版本3.6.9: device_create -> device_register -> device_add -> device_add_attrs -> devic ...
- linux下eclipse
最近想学习C++,所以就重新安装了linux系统,虽然这两者没有什么联系,但是我还是比较喜欢linux系统,所以在linux下安装了Eclipse,想起了当初学习Red Hat 9.0时的痛苦场景,哎 ...
- .NET 5 开源工作流框架elsa技术研究
今天假期第一天,研究了.NET 5开源工作流框架elsa,现在分享给大家. 一.框架简介 elsa是一个开源的.NET Standard 工作流框架,官方网站:https://elsa-workflo ...
- 数据库分库分表容量划分建议参考阿里云DRDS原则
做分库分表的时候 一直想知道分库分表容量的最优规则有什么好的建议,以下是参考阿里云 DRDS 分库分表的规则,还是有一定的参考意义 .
- 2020再见&新的计划(建立Android体系架构)
2020,再见 关于2020,我心中有四个关键词: 疫情 年初突如其来的疫情,打破了原本生活的节奏,也没想到会笼罩全世界整整一年,希望这个世界早点好起来吧. 科比 初三的早晨,噩耗传来,我一度不敢相信 ...
- MySQL中in('5,6,7')只取第一个id为5对应的数据的思考
通过阅读本文你可以更好的理解两个知识点: 1.#{}与${}在实际项目中的使用,避免在项目中使用不当造成不可预知的Bug; 2.MySQL中in里面如果是字符串的话,为什么只取第一个对应的数据,eg: ...
- App控件定位
本文将分享Android相关基础知识和Android APP控件定位工具的使用方法. Android基础知识 Android布局 Android是通过容器的布局属性来管理子控件的位置关系(iOS去掉了 ...
- Log4j配置按照文件大小和日期分割日志文件
目录 Log4j 下载地址 文件大小分割日志文件 以日期分割每天产生一个日志文件 自定义信息输出到日志文件 Log4j 下载地址 Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控 ...