Endian.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Endian operations.
  3. *
  4. * @author n1474335 [n1474335@gmail.com]
  5. * @copyright Crown Copyright 2016
  6. * @license Apache-2.0
  7. *
  8. * @namespace
  9. */
  10. var Endian = {
  11. /**
  12. * @constant
  13. * @default
  14. */
  15. DATA_FORMAT: ["Hex", "Raw"],
  16. /**
  17. * @constant
  18. * @default
  19. */
  20. WORD_LENGTH: 4,
  21. /**
  22. * @constant
  23. * @default
  24. */
  25. PAD_INCOMPLETE_WORDS: true,
  26. /**
  27. * Swap endianness operation.
  28. *
  29. * @param {string} input
  30. * @param {Object[]} args
  31. * @returns {string}
  32. */
  33. runSwapEndianness: function(input, args) {
  34. var dataFormat = args[0],
  35. wordLength = args[1],
  36. padIncompleteWords = args[2],
  37. data = [],
  38. result = [],
  39. words = [],
  40. i = 0,
  41. j = 0;
  42. if (wordLength <= 0) {
  43. return "Word length must be greater than 0";
  44. }
  45. // Convert input to raw data based on specified data format
  46. switch (dataFormat) {
  47. case "Hex":
  48. data = Utils.fromHex(input);
  49. break;
  50. case "Raw":
  51. data = Utils.strToByteArray(input);
  52. break;
  53. default:
  54. data = input;
  55. }
  56. // Split up into words
  57. for (i = 0; i < data.length; i += wordLength) {
  58. var word = data.slice(i, i + wordLength);
  59. // Pad word if too short
  60. if (padIncompleteWords && word.length < wordLength){
  61. for (j = word.length; j < wordLength; j++) {
  62. word.push(0);
  63. }
  64. }
  65. words.push(word);
  66. }
  67. // Swap endianness and flatten
  68. for (i = 0; i < words.length; i++) {
  69. j = words[i].length;
  70. while (j--) {
  71. result.push(words[i][j]);
  72. }
  73. }
  74. // Convert data back to specified data format
  75. switch (dataFormat) {
  76. case "Hex":
  77. return Utils.toHex(result);
  78. case "Raw":
  79. return Utils.byteArrayToUtf8(result);
  80. default:
  81. return result;
  82. }
  83. },
  84. };