2013
Dec
14

在 Javascript 中,如何將 字串轉成 Binary ,以及將 Binary 轉成 Ascii 字串 呢?

字串轉成二進位

string to binary
  1.  
  2. function str2bin(str) {
  3. n = str.length;
  4. bin = "";
  5. for (var i = 0 ; i< n ; i++) {
  6. s = str.substr(i, 1);
  7. bin += str_pad(s.charCodeAt(0).toString(2), 8, "0", "left");
  8. }
  9. return bin;
  10. }
  11.  
  12. function str_pad(str, len, chr, dir)
  13. {/*{{{*/
  14. str = str.toString();
  15. len = (typeof len == "number") ? len : 0;
  16. chr = (typeof chr == "string") ? chr : " ";
  17. dir = (/left|right|both/i).test(dir) ? dir : "right";
  18. var repeat = function(c, l) {
  19.  
  20. var repeat = "";
  21. while (repeat.length < l) {
  22. repeat += c;
  23. }
  24. return repeat.substr(0, l);
  25. }
  26. var diff = len - str.length;
  27. if (diff > 0) {
  28. switch (dir) {
  29. case "left":
  30. str = "" + repeat(chr, diff) + str;
  31. break;
  32. case "both":
  33. var half = repeat(chr, Math.ceil(diff / 2));
  34. str = (half + str + half).substr(1, len);
  35. break;
  36. default:
  37. str = "" + str + repeat(chr, diff);
  38. }
  39. }
  40. return str;
  41. }/*}}}*/

二進位轉成字串

binary to Ascii string
  1. function bin2str(text) {
  2. var output = "";
  3. for (var i = 0 ; i < text.length; i+= 8) {
  4. var c = 0;
  5. for (var j=0; j < 8 ; j++) {
  6. c <<= 1;
  7. c |= parseInt(text[i + j]);
  8. }
  9. output += String.fromCharCode(c);
  10. }
  11. return output;
  12. }
  13.  
  14.  


回應 (Leave a comment)