Skip to content

Instantly share code, notes, and snippets.

@KensakuKOMATSU
Last active December 23, 2015 10:19
Show Gist options
  • Save KensakuKOMATSU/6620342 to your computer and use it in GitHub Desktop.
Save KensakuKOMATSU/6620342 to your computer and use it in GitHub Desktop.
StringのArrayBufferへの変換と戻し(Blob() が無いと動かないので注意)
var str2buff = function(str){
var ab_ = new ArrayBuffer(new Blob([str]).size);
var bytes_ = new Uint8Array(ab_);
var n = str.length,
idx = -1,
i, c;
for(i = 0; i < n; ++i){
c = str.charCodeAt(i);
if(c <= 0x7F){
bytes_[++idx] = c;
} else if(c <= 0x7FF){
bytes_[++idx] = 0xC0 | (c >>> 6);
bytes_[++idx] = 0x80 | (c & 0x3F);
} else if(c <= 0xFFFF){
bytes_[++idx] = 0xE0 | (c >>> 12);
bytes_[++idx] = 0x80 | ((c >>> 6) & 0x3F);
bytes_[++idx] = 0x80 | (c & 0x3F);
} else {
bytes_[++idx] = 0xF0 | (c >>> 18);
bytes_[++idx] = 0x80 | ((c >>> 12) & 0x3F);
bytes_[++idx] = 0x80 | ((c >>> 6) & 0x3F);
bytes_[++idx] = 0x80 | (c & 0x3F);
}
}
return bytes_;
}
var buff2str = function(buff){
var size = buff.length;
var i = 0, str = '', c, code;
while(i < size){
c = buff[i];
if ( c < 128){
str += String.fromCharCode(c);
i++;
} else if ((c ^ 0xc0) < 32){
code = ((c ^ 0xc0) << 6) | (buff[i+1] & 63);
str += String.fromCharCode(code);
i += 2;
} else {
code = ((c & 15) << 12) | ((buff[i+1] & 63) << 6) |
(buff[i+2] & 63);
str += String.fromCharCode(code);
i += 3;
}
}
return str;
}
// test
var text = "abc";
var b = str2buff(text);
console.log(buff2str(b));
text = "こんにちは";
b = str2buff(text);
console.log(buff2str(b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment