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

Java Dize dizisi için ArrayList içeren...
Nasıl python tamsayılar dizeleri dönüş...
Nasıl Java UTF8 bayt dizileri için Diz...
En iyi karakter kümeleri arasında meti...
Nasıl Listesi< tüm dizeleri Dönüştür...