integerToNBytes.js 1.1 KB

12345678910111213141516171819202122232425262728
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $Number = GetIntrinsic('%Number%');
  4. var $BigInt = GetIntrinsic('%BigInt%', true);
  5. module.exports = function integerToNBytes(intValue, n, isLittleEndian) {
  6. var Z = typeof intValue === 'bigint' ? $BigInt : $Number;
  7. /*
  8. if (intValue >= 0) { // step 3.d
  9. // Let rawBytes be a List containing the n-byte binary encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
  10. } else { // step 3.e
  11. // Let rawBytes be a List containing the n-byte binary 2's complement encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
  12. }
  13. */
  14. if (intValue < 0) {
  15. intValue >>>= 0; // eslint-disable-line no-param-reassign
  16. }
  17. var rawBytes = [];
  18. for (var i = 0; i < n; i++) {
  19. rawBytes[isLittleEndian ? i : n - 1 - i] = $Number(intValue & Z(0xFF));
  20. intValue >>= Z(8); // eslint-disable-line no-param-reassign
  21. }
  22. return rawBytes; // step 4
  23. };