0

I need to set 50th bit of a number. But bitwise operators work in javascript only on lower 32 bits. So I my solution is:

function set50thBitOf(x) {
  hi=Math.trunc(x/2**32);
  lo=x%2**32;
  res=(hi|2**(50-32-1))*2**32+lo;
  return res;
}

Is there better way?

user2106769
  • 445
  • 5
  • 15
  • are you sure that you get the wanted result with a bitwise OR? – Nina Scholz Jan 20 '18 at 17:51
  • @NinaScholz ,yes it works, but I'm afraid about performance, because of division and multiplication used for spiting 64bit number to two 32bit parts and back – user2106769 Jan 20 '18 at 18:00
  • I can't think of another way to do it. Most other Q&A's on this topic suggest the same thing. Generally speaking, mathematical operations are very fast in modern JS engines, so I wouldn't worry about performance. https://stackoverflow.com/questions/3637702/how-to-do-bitwise-and-in-javascript-on-variables-that-are-longer-than-32-bit You could look into a BigInt JS library (there are several) which work with the numbers as strings, but then I would worry about performance. – skyline3000 Jan 20 '18 at 18:20
  • You can try `x += (x % 2**50 < 2**49) * 2**49` or `x += (x % 2**50 < 2**49) ? 2**49 : 0` though no guarantees that it's better. Or `x += ((x / 2**32) & 2**17) ? 0 : 2**49`? – Veedrac Jan 22 '18 at 03:36

0 Answers0