FewWords
FewWords

Reputation: 675

Bitshift operator on unsigned short in NodeJS

I am trying to perform a Bitwise NOT on an unsigned int in nodeJS/JavaScript. In my understanding every bitwise operator is done on a signed 32bit integer which makes it confusing for me when I want to do it on an unsigned 16bit integer (short). This is what I want to do:

c#
ushort value = 41003;
value = (ushort)~value;
//Value is now 24532 which is correct

nodeJS
var value = 41003;
value = ~value;
//value is now -41004 which is NOT correct

How do I convert the last value to an unsigned 16bit int in nodeJS/JavaScript?

Upvotes: 1

Views: 1273

Answers (3)

Alex Michailidis
Alex Michailidis

Reputation: 4143

Or you could simply use the Uint16Array

(new Uint16Array([~41003]))[0] //24532

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could use a the maximum value of a 16 bit number and perform a bitwise XOR ^.

function not16Bit(v) {
    return ((1 << 16) - 1) ^  v;
}
 
console.log(not16Bit(41003)); // 24532
console.log(not16Bit(24532)); // 41003

Upvotes: 0

mscdex
mscdex

Reputation: 106706

You could just do a bitwise AND to get the same result:

value = ~value & 0xFFFF;

Upvotes: 2

Related Questions