You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
850 B

4 years ago
  1. var charenc = {
  2. // UTF-8 encoding
  3. utf8: {
  4. // Convert a string to a byte array
  5. stringToBytes: function(str) {
  6. return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
  7. },
  8. // Convert a byte array to a string
  9. bytesToString: function(bytes) {
  10. return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
  11. }
  12. },
  13. // Binary encoding
  14. bin: {
  15. // Convert a string to a byte array
  16. stringToBytes: function(str) {
  17. for (var bytes = [], i = 0; i < str.length; i++)
  18. bytes.push(str.charCodeAt(i) & 0xFF);
  19. return bytes;
  20. },
  21. // Convert a byte array to a string
  22. bytesToString: function(bytes) {
  23. for (var str = [], i = 0; i < bytes.length; i++)
  24. str.push(String.fromCharCode(bytes[i]));
  25. return str.join('');
  26. }
  27. }
  28. };
  29. module.exports = charenc;