SORU
6 AĞUSTOS 2011, CUMARTESİ


Dizeleri arasında dönüştürmek ve ArrayBuffers

Verimli ArrayBuffers ve tersi için JavaScript dizeleri dönüştürmek için yaygın olarak kabul gören bir yöntem var mı? Özellikle, localStorage bir ArrayBuffer içeriğini yazmak ve tekrar okumak istiyorum.

CEVAP
15 HAZİRAN 2012, Cuma


Dennis ve Blob kullanarak gengkev çözümler FileReader iş olmasına rağmen, bu yaklaşımı tavsiye etmem. Basit bir sorun için zaman uyumsuz bir yaklaşım olduğunu, ve doğrudan bir çözüm daha yavaş. Daha basit ve çok daha hızlı bir çözüm ile html5rocks bir yazı hazırladım: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

Ve çözüm:

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;
}

DÜZENLEME:

Encoding API helps solving the string conversion sorun. Yukarıda özgün makale Html5Rocks.com Jeff Posnik yanıtı kontrol edin.

Alıntı:

Kodlama API basit ham bayt ve yerel JavaScript dizeleri arasında çevirmek için, birlikte çalışmak için gerekli olan ne olursa olsun yapar.

<pre id="results"></pre>

<script>
  if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
      'utf8.bin': 'utf-8',
      'utf16le.bin': 'utf-16le',
      'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
      fetchAndDecode(file, filesToEncoding[file]);
    });
  } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
  }

  // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
  function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
      if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent  = decodedString   '\n';
      } else {
        console.error('Error while requesting', file, this);
      }
    };
    xhr.send();
  }
</script>

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • funbro1

    funbro1

    11 Aralık 2007
  • Muse

    Muse

    28 EYLÜL 2006
  • YouChewBu

    YouChewBu

    26 Ocak 2009