1

I need to represent UNIX time as two numbers in JavaScript - first 32 bits and next 16 bits (would be enough for some time).

So, having a number that's potentially greater then 2^32 (but less then 2^48), I want to get its 0-31 bits part and 32-47 bits part as two numbers. Getting the first number is easy but the second is not due to 32-bitness of JavaScript's bit-wise operators.

I could do something like

longNumber.toString(2).substring(0, longNumber.length - 32)

to get the binary value of the second number and convert it to decimal. But I wonder is it possible to do it without string conversions?

Tvaroh
  • 6,645
  • 4
  • 51
  • 55
  • I guess it's possible if you do the divisions in multiple parts, but I don't this there is going to be a clear and brief solution like the one you have now. If you stick with string manipulation, you could stick with hexadecimal, but that doesn't improve things that much either. – GolezTrol Dec 01 '15 at 08:11

1 Answers1

1

Came up with this (it additionally splits first 32 bits into two 16 bits):

function splitTime(time) {
  const first32 = time & 0xFFFFFFFF;

  const first16 = first32 & 0xFFFF;
  const second16 = first32 >>> 16;

  const third16 = Math.floor((time / 0xFFFFFFFF) & 0xFFFF);

  return [first16, second16, third16];
}
Tvaroh
  • 6,645
  • 4
  • 51
  • 55