bytesAsInteger.js 995 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $pow = GetIntrinsic('%Math.pow%');
  4. var $Number = GetIntrinsic('%Number%');
  5. var $BigInt = GetIntrinsic('%BigInt%', true);
  6. module.exports = function bytesAsInteger(rawBytes, elementSize, isUnsigned, isBigInt) {
  7. var Z = isBigInt ? $BigInt : $Number;
  8. // this is common to both branches
  9. var intValue = Z(0);
  10. for (var i = 0; i < rawBytes.length; i++) {
  11. intValue += Z(rawBytes[i] * $pow(2, 8 * i));
  12. }
  13. /*
  14. Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.
  15. */
  16. if (!isUnsigned) { // steps 5-6
  17. // Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian 2's complement number of bit length elementSize × 8.
  18. var bitLength = elementSize * 8;
  19. if (rawBytes[elementSize - 1] & 0x80) {
  20. intValue -= Z($pow(2, bitLength));
  21. }
  22. }
  23. return intValue; // step 7
  24. };