HTML5 TypeArray和Unicode 字符之间转换

时间:2021-12-09 15:13:06

1.Uint32Array测试成功

    // Uint32Array 测试成功
//字符串转为ArrayBuffer对象
function strToab() {
var str = '张三丰';
var buf = new ArrayBuffer(str.length * 4);
var bufView = new Uint32Array(buf);
for (var i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
console.info(bufView);
}
strToab();
//将 ArrayBuffer对象,转换成字符串
function abTostr() {
var bufView = new Uint32Array([24352, 19977, 20016]); //[24352, 19977, 20016]
console.info(bufView);
var result = '';
for (var i = 0; i < bufView.length; i++) {
result += String.fromCharCode(bufView[i]);
}
console.info(result); //输出结果为空
}
abTostr();

2.Uint16Array测试成功

    //Uint16Array 测试成功
//字符串转为ArrayBuffer对象
function strToab() {
var str = '张三丰';
var buf = new ArrayBuffer(str.length * 2);
var bufView = new Uint16Array(buf);
for (var i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
console.info(bufView);
}
strToab();
//将 ArrayBuffer对象,转换成字符串
function abTostr() {
//方式1,无效
//var buf = new ArrayBuffer([24352, 19977, 20016]);
//var bufView = new Uint16Array(buf); //获得的结果为空
//方式2,有效
var bufView = new Uint16Array([24352, 19977, 20016]); //[24352, 19977, 20016]
var result = '';
for (var i = 0; i < bufView.length; i++) {
result += String.fromCharCode(bufView[i]);
}
console.info(result); //输出结果 '张三丰'
}
abTostr();

3.Uint8Array 测试失败

        //Uint8Array 测试失败
//字符串转为ArrayBuffer对象
function strToab() {
var str = '张三丰';
var buf = new ArrayBuffer(str.length * 2);
var bufView = new Uint8Array(buf);
for (var i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
console.info(bufView);
}
strToab();
//将 ArrayBuffer对象,转换成字符串
function abTostr() {
var buf = new ArrayBuffer([24352, 19977, 20016]);
// var bufView = new Uint16Array(buf); //获得的结果为空
var bufView = new Uint8Array([32, 9, 48]); //[24352, 19977, 20016]
console.info(bufView);
var result = '';
for (var i = 0; i < bufView.length; i++) {
result += String.fromCharCode(bufView[i]);
}
console.info(result); //输出结果为空
}
abTostr();