utf8.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Obtained from http://homepage3.nifty.com/aokura/jscript/index.html
  3. * The webpage says, among other things:
  4. * * ソースコードの全てあるいは一部を使用したことにより生じた損害に関しては一切責任を負いません。
  5. * * ソースコードの使用、配布に制限はありません。ご自由にお使いください。
  6. * * 動作チェックが不充分な場合もありますので、注意してください。
  7. *
  8. * Which, loosely translated, means:
  9. * * The author takes no responsibility for damage which occurs due to the use of this code.
  10. * * There is no restriction on the use and distribution of the source code. Please use freely.
  11. * * Please be careful, testing may have been insufficient.
  12. */
  13. /**********************************************************************
  14. *
  15. * Unicode ⇔ UTF-8
  16. *
  17. * Copyright (c) 2005 AOK <soft@aokura.com>
  18. *
  19. **********************************************************************/
  20. function _to_utf8(s) {
  21. var c, d = "";
  22. for (var i = 0; i < s.length; i++) {
  23. c = s.charCodeAt(i);
  24. if (c <= 0x7f) {
  25. d += s.charAt(i);
  26. } else if (c >= 0x80 && c <= 0x7ff) {
  27. d += String.fromCharCode(((c >> 6) & 0x1f) | 0xc0);
  28. d += String.fromCharCode((c & 0x3f) | 0x80);
  29. } else {
  30. d += String.fromCharCode((c >> 12) | 0xe0);
  31. d += String.fromCharCode(((c >> 6) & 0x3f) | 0x80);
  32. d += String.fromCharCode((c & 0x3f) | 0x80);
  33. }
  34. }
  35. return d;
  36. }
  37. function _from_utf8(s) {
  38. var c, d = "", flag = 0, tmp;
  39. for (var i = 0; i < s.length; i++) {
  40. c = s.charCodeAt(i);
  41. if (flag == 0) {
  42. if ((c & 0xe0) == 0xe0) {
  43. flag = 2;
  44. tmp = (c & 0x0f) << 12;
  45. } else if ((c & 0xc0) == 0xc0) {
  46. flag = 1;
  47. tmp = (c & 0x1f) << 6;
  48. } else if ((c & 0x80) == 0) {
  49. d += s.charAt(i);
  50. } else {
  51. flag = 0;
  52. }
  53. } else if (flag == 1) {
  54. flag = 0;
  55. d += String.fromCharCode(tmp | (c & 0x3f));
  56. } else if (flag == 2) {
  57. flag = 3;
  58. tmp |= (c & 0x3f) << 6;
  59. } else if (flag == 3) {
  60. flag = 0;
  61. d += String.fromCharCode(tmp | (c & 0x3f));
  62. } else {
  63. flag = 0;
  64. }
  65. }
  66. return d;
  67. }