3

first of all I'm sorry for the dumb question but I'm new with nodejs. I read from a socket a 64bit little endian signed integer, and put it on a Buffer, so let's say i have the number 256 represented as:

<Buffer 00 01 00 00 00 00 00 00>

Since the Buffer class has only readInt32LE and readUInt32LE how can i convert this buffer to its equivalent js number, using 32 bit operations ? Should i read two 32bit big endian numbers and then somehow bitwise or them ? should i read them little endian ?

Thanks

0

1 Answer 1

3

ECMA Section 8.5 - Numbers

Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type (indeed, the integer 0 has two representations, +0 and −0).

Javascript uses internally 64 bit floating numbers, wich means you can only represent exactly numbers up to 253, or 9007199254740992. If it's ok for you, you can use following code to read 64 bit signed/unsigned int into 64 bit float:

function readUInt64(buff, offset) {
  return buff.readInt32LE(offset) + 0x100000000*buff.readUInt32LE(offset + 4);
}

function readInt64(buff, offset) {
   var word0 = buff.readUInt32LE(offset);
   var word1 = buff.readUInt32LE(offset+4);
   if (!(word1 & 0x80000000))
      return word0 + 0x100000000*word1;
   return -((((~word1)>>>0) * 0x100000000) + ((~word0)>>>0) + 1);
}

If you need exact representation - use bignumber.js library

function readUInt64(buff, offset) {
   var word0 = buff.readUInt32LE(offset);
   var word1 = buff.readUInt32LE(offset+4);
   return new BigNumber(word0).plus(new BigNumber(word1).times(0x100000000));
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.