Last active
May 16, 2024 10:35
-
-
Save kawanet/352a2ed1d1656816b2bc to your computer and use it in GitHub Desktop.
String と ArrayBuffer の相互変換 JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 文字列から ArrayBuffer への変換 | |
function string_to_buffer(src) { | |
return (new Uint16Array([].map.call(src, function(c) { | |
return c.charCodeAt(0) | |
}))).buffer; | |
} | |
// ArrayBuffer から文字列への変換 | |
function buffer_to_string(buf) { | |
return String.fromCharCode.apply("", new Uint16Array(buf)) | |
} | |
// ただし、文字列が長すぎる場合は RangeError: Maximum call stack size exceeded. が発生してしまう。 | |
// 以下は1024バイト単位に分割して処理する場合 | |
function large_buffer_to_string(buf) { | |
var tmp = []; | |
var len = 1024; | |
for (var p = 0; p < buf.byteLength; p += len) { | |
tmp.push(buffer_to_string(buf.slice(p, p + len))); | |
} | |
return tmp.join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment