2013
Dec
14
在 Javascript 中,如何將 字串轉成 Binary ,以及將 Binary 轉成 Ascii 字串 呢?
字串轉成二進位
string to binary
- function str2bin(str) {
- n = str.length;
- bin = "";
- for (var i = 0 ; i< n ; i++) {
- s = str.substr(i, 1);
- bin += str_pad(s.charCodeAt(0).toString(2), 8, "0", "left");
- }
- return bin;
- }
- function str_pad(str, len, chr, dir)
- {/*{{{*/
- str = str.toString();
- len = (typeof len == "number") ? len : 0;
- chr = (typeof chr == "string") ? chr : " ";
- dir = (/left|right|both/i).test(dir) ? dir : "right";
- var repeat = function(c, l) {
- var repeat = "";
- while (repeat.length < l) {
- repeat += c;
- }
- return repeat.substr(0, l);
- }
- var diff = len - str.length;
- if (diff > 0) {
- switch (dir) {
- case "left":
- str = "" + repeat(chr, diff) + str;
- break;
- case "both":
- var half = repeat(chr, Math.ceil(diff / 2));
- str = (half + str + half).substr(1, len);
- break;
- default:
- str = "" + str + repeat(chr, diff);
- }
- }
- return str;
- }/*}}}*/
二進位轉成字串
binary to Ascii string
- function bin2str(text) {
- var output = "";
- for (var i = 0 ; i < text.length; i+= 8) {
- var c = 0;
- for (var j=0; j < 8 ; j++) {
- c <<= 1;
- c |= parseInt(text[i + j]);
- }
- output += String.fromCharCode(c);
- }
- return output;
- }