mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-28 21:32:20 +00:00
Merge pull request #858 from waitingsong/arraybuffer
docs(arrayBuffer): 更新 ArrayBuffer/字符串 相互转换函数,支持多语言及多编码
This commit is contained in:
commit
06ee0bbc19
@ -448,34 +448,40 @@ Float64Array.BYTES_PER_ELEMENT // 8
|
|||||||
|
|
||||||
### ArrayBuffer 与字符串的互相转换
|
### ArrayBuffer 与字符串的互相转换
|
||||||
|
|
||||||
`ArrayBuffer`转为字符串,或者字符串转为`ArrayBuffer`,有一个前提,即字符串的编码方法是确定的。假定字符串采用 UTF-16 编码(JavaScript 的内部编码方式),可以自己编写转换函数。
|
`ArrayBuffer` 和字符串相互转换, 使用原生 `TextEncoder` `TextDecoder` 类方法转换任何字符集字符串
|
||||||
|
outputEncoding 输出编码一般保持默认值(utf-8),可选值见文档:
|
||||||
|
- https://encoding.spec.whatwg.org
|
||||||
|
- https://nodejs.org/api/util.html#util_whatwg_supported_encodings
|
||||||
|
|
||||||
```javascript
|
```ts
|
||||||
// ArrayBuffer 转为字符串,参数为 ArrayBuffer 对象
|
/**
|
||||||
function ab2str(buf) {
|
* Convert ArrayBuffer/TypedArray to String via TextDecoder
|
||||||
// 注意,如果是大型二进制数组,为了避免溢出,
|
*
|
||||||
// 必须一个一个字符地转
|
* @see https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
|
||||||
if (buf && buf.byteLength < 1024) {
|
*/
|
||||||
return String.fromCharCode.apply(null, new Uint16Array(buf));
|
function ab2str(
|
||||||
}
|
input: ArrayBuffer | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array,
|
||||||
|
outputEncoding: string = 'utf8',
|
||||||
const bufView = new Uint16Array(buf);
|
): string {
|
||||||
const len = bufView.length;
|
const decoder = new TextDecoder(outputEncoding)
|
||||||
const bstr = new Array(len);
|
return decoder.decode(input)
|
||||||
for (let i = 0; i < len; i++) {
|
|
||||||
bstr[i] = String.fromCharCode.call(null, bufView[i]);
|
|
||||||
}
|
|
||||||
return bstr.join('');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 字符串转为 ArrayBuffer 对象,参数为字符串
|
/**
|
||||||
function str2ab(str) {
|
* Convert String to ArrayBuffer via TextEncoder
|
||||||
const buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
|
*
|
||||||
const bufView = new Uint16Array(buf);
|
* @see https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder
|
||||||
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
*/
|
||||||
bufView[i] = str.charCodeAt(i);
|
function str2ab(input: string): ArrayBuffer {
|
||||||
}
|
const view = str2Uint8Array(input)
|
||||||
return buf;
|
return view.buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert String to Uint8Array */
|
||||||
|
function str2Uint8Array(input: string): Uint8Array {
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const view = encoder.encode(input)
|
||||||
|
return view
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user