Hex.mjs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * Byte representation functions.
  3. *
  4. * @author n1474335 [n1474335@gmail.com]
  5. * @copyright Crown Copyright 2016
  6. * @license Apache-2.0
  7. */
  8. import Utils from "../Utils";
  9. /**
  10. * Convert a byte array into a hex string.
  11. *
  12. * @param {Uint8Array|byteArray} data
  13. * @param {string} [delim=" "]
  14. * @param {number} [padding=2]
  15. * @returns {string}
  16. *
  17. * @example
  18. * // returns "0a 14 1e"
  19. * toHex([10,20,30]);
  20. *
  21. * // returns "0a:14:1e"
  22. * toHex([10,20,30], ":");
  23. */
  24. export function toHex(data, delim=" ", padding=2) {
  25. if (!data) return "";
  26. let output = "";
  27. for (let i = 0; i < data.length; i++) {
  28. output += data[i].toString(16).padStart(padding, "0") + delim;
  29. }
  30. // Add \x or 0x to beginning
  31. if (delim === "0x") output = "0x" + output;
  32. if (delim === "\\x") output = "\\x" + output;
  33. if (delim.length)
  34. return output.slice(0, -delim.length);
  35. else
  36. return output;
  37. }
  38. /**
  39. * Convert a byte array into a hex string as efficiently as possible with no options.
  40. *
  41. * @param {byteArray} data
  42. * @returns {string}
  43. *
  44. * @example
  45. * // returns "0a141e"
  46. * toHex([10,20,30]);
  47. */
  48. export function toHexFast(data) {
  49. if (!data) return "";
  50. const output = [];
  51. for (let i = 0; i < data.length; i++) {
  52. output.push((data[i] >>> 4).toString(16));
  53. output.push((data[i] & 0x0f).toString(16));
  54. }
  55. return output.join("");
  56. }
  57. /**
  58. * Convert a hex string into a byte array.
  59. *
  60. * @param {string} data
  61. * @param {string} [delim]
  62. * @param {number} [byteLen=2]
  63. * @returns {byteArray}
  64. *
  65. * @example
  66. * // returns [10,20,30]
  67. * fromHex("0a 14 1e");
  68. *
  69. * // returns [10,20,30]
  70. * fromHex("0a:14:1e", "Colon");
  71. */
  72. export function fromHex(data, delim, byteLen=2) {
  73. delim = delim || "Auto";
  74. if (delim !== "None") {
  75. const delimRegex = delim === "Auto" ? /[^a-f\d]/gi : Utils.regexRep(delim);
  76. data = data.replace(delimRegex, "");
  77. }
  78. const output = [];
  79. for (let i = 0; i < data.length; i += byteLen) {
  80. output.push(parseInt(data.substr(i, byteLen), 16));
  81. }
  82. return output;
  83. }
  84. /**
  85. * To Hexadecimal delimiters.
  86. */
  87. export const TO_HEX_DELIM_OPTIONS = ["Space", "Comma", "Semi-colon", "Colon", "Line feed", "CRLF", "0x", "\\x", "None"];
  88. /**
  89. * From Hexadecimal delimiters.
  90. */
  91. export const FROM_HEX_DELIM_OPTIONS = ["Auto"].concat(TO_HEX_DELIM_OPTIONS);