JavaScript is not enabled on browser.
[Reference]developer.mozilla.org
変換処理 Byte Order指定の実装方法
前提 ・Uint16Array等の型付き配列のByte Orderは環境依存
 ⇒ DataViewで代替
・1Byte文字の符号位置:uint8 code-point<256
 ⇔ 8bitのLatin1(7bitのASCII文字の拡張)
・1Byte文字列:1Byte文字の文字列
 ⇔ Base64文字列(Multi-Byte文字列対応のBlob標準)
文字列 ⇒
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;
};