Home > Net >  Inconsistency between C# and Javascript bitwise operator
Inconsistency between C# and Javascript bitwise operator

Time:01-02

Given the following code:

uint HASHTABLE = 1917507215;
for (uint i = 5; i != 0; i--)
        {
            HASHTABLE = (HASHTABLE ^ ((HASHTABLE << 10 ^ HASHTABLE) << 9 ^ HASHTABLE) << 5) & 0x7fffffff ^ (((HASHTABLE << 7 ^ HASHTABLE) << 10 ^ HASHTABLE) << 9 ^ HASHTABLE) << 5;
            HASHTABLE = HASHTABLE >> 1 | (HASHTABLE & 1) << 0x1f;
        }

I am trying to convert this code to JavaScript, but I have noticed that there has been an inconsistency in the calculation. In C#, the value of the HASHTABLE after the loop finished, is 1871861428 While in Javascript, the value is -275622220.

I suspect the problem comes from the fact that in c#, the value is supposed to be unsigned. Besides, Javascript can do bitwise operators up to 32 bits.

Which is why, I have attempted to go ahead and use the Long library (https://www.npmjs.com/package/long)

I have therefore set my HASHTABLE value to be Long.fromValue(HASHTABLE, true), and proceeded with doing the operations using Long, as follows:

hashTable = Long.fromValue(hashTable, true);
for (let i = 5; i != 0; i--) {
    hashTable = hashTable.xor(
        hashTable.shiftLeft(10).xor(hashTable).shiftLeft(9).xor(hashTable).shiftLeft(5)
      ).and(0x7fffffff).xor(
        hashTable.shiftLeft(7).xor(hashTable).shiftLeft(10).xor(hashTable).shiftLeft(9).xor(hashTable).shiftLeft(5)
    );
    hashTable = hashTable.shiftRight(1).or(hashTable.and(1).shiftLeft(0x1f));
}
hashTable = hashTable.toInt();

However, even after using Long, my HASHTABLE value will be 4019345076 in Javascript.

Basically, in Javascript I will get 0xEF9256B4 while in C# I will correctly get 0x6F9256B4, the difference beeing that the 32nd (most signifficant bit) is set in JavaScript, and in C# it isn't.

What am I missing here, and why, even after using the Long library, there is this inconsistency between JavaScript and C#?

CodePudding user response:

see Unsigned_right_shift >>>

let HASHTABLE = 1917507215;
for (let i = 5; i != 0; i--) {
  HASHTABLE = (HASHTABLE ^ ((HASHTABLE << 10 ^ HASHTABLE) << 9 ^ HASHTABLE) << 5) & 0x7fffffff ^ (((HASHTABLE << 7 ^ HASHTABLE) << 10 ^ HASHTABLE) << 9 ^ HASHTABLE) << 5;
  HASHTABLE = HASHTABLE >>> 1 | (HASHTABLE & 1) << 0x1f;
}
console.log(HASHTABLE);

  • Related