文字列 ⇒
1Byte文字列
|
実装手順と実装codeを以下に示す
-
2Byte大のArrayBufferを作る
-
ArrayBufferを操作するDataViewを作る
-
DataViewを介して
JavaScript文字列で扱うUTF-16 code-unitをArrayBufferに代入する
-
既定ではBEで代入されるので、LEで代入する場合は第3引数を追加する
-
BE/LEを指定して直列化したArrayBufferからuint8のDataViewを作る
-
直列化した順番にuint8 code-pointを1Byte文字に変換する
My_entry.conv.prototype.str2binary = function(str, isLE){
var self = this;
var _binary = "";
var buffer = new ArrayBuffer(2);
var view = new DataView(buffer, 0);
var arr_uint16 = self.str2code_utf16(str, 10);
arr_uint16.forEach(function(uint16){
view.setUint16(0, uint16, isLE);
var arrb_uint8 = new Uint8Array(buffer);
Array.prototype.forEach.call(arrb_uint8, function(uint8, i){
_binary += String.fromCharCode(uint8);
});
});
return _binary;
};
|
1Byte文字列
⇒ 文字列
|
実装手順と実装codeを以下に示す
-
binary大のArrayBufferを作る
-
ArrayBufferを操作するDataViewを作る
-
DataViewを介して
1Byte文字をuint8 code-pointに変換してArrayBufferに代入する
-
さらにDataViewを介して
ArrayBufferからBE/LEを指定して2Byte単位で取得したuint16の配列を作る
-
取得した順番にuint16 code-pointを文字列に変換する
My_entry.conv.prototype.binary2str = function(binary, isLE){
var self = this;
var _str = "";
var buffer = new ArrayBuffer(binary.length+1);
var view = new DataView(buffer, 0);
Array.prototype.forEach.call(binary, function(byte, i){
view.setUint8(i, binary.charCodeAt(i));
});
var arr_uint16 = [];
for(var i=0, len=(binary.length+1)>>1; i<len; ++i){
arr_uint16[i] = view.getUint16(i<<1, isLE);
}
arr_uint16.forEach(function(uint16, i){
_str += String.fromCharCode(uint16);
});
return _str;
};
|