Roberto Rossi
Roberto Rossi

Reputation: 97

Javascript bitwise to c#

I have some issue to convert a javascript code into c# the issue is with bitwise operator:

Javascript function: return (s - (s | 0x0)) * 0x100000000 | 0x0;

C# function; return (long)((s - ((long)s)) * 0x100000000);

If s = 1.7320508075688772 on Javascript report -1150833019 on c# report 3144134277

other example can be Javascript: (1779033703 << 0x1e) = -1073741824 c# (1779033703 << 0x1e) = 1910222893216694272

What i need is translate Javascript function into c# with same number result.

Thanks for help.

Upvotes: 0

Views: 156

Answers (2)

Guven Sezgin Kurt
Guven Sezgin Kurt

Reputation: 1339

You can't expect the same behavior on C# by default. Because:

  • In JavaScript, a number is stored as a 64-bit floating point number but the bit-wise operation is performed on a 32-bit binary number
  • So to perform a bit-operation JavaScript converts the number into a 32-bit binary number, perform the operation and convert back the result to a 64-bit number.

So in your case you might be trying to cast a 64-bit number to 32-bit one and get a faulty result from there. Which in C# it wouldn't be a good thing to have in my opinion.

Upvotes: 1

GokuMizuno
GokuMizuno

Reputation: 543

So, there are a few things going on here.

  1. You have a type mismatch in your JavaScript. In Hex, 3144134277 is BB67AE85, and -1150833019 is FFFFFFFFBB67AE85. So, we can see that the JavaScript int32 is being implicitly converted to an unsigned int64.

  2. You can't bitshift by 0. Bitshifting is dividing by 2^n, where n is, in this case, 0. That returns the same number, as 2^0 = 1.

  3. (long)((ulong)(…) That's a double cast, and is considered bad form. Your number literal will be cast to an unsigned long, then cast again to a long. This just wastes cycles.

  4. Your cast is a C style cast, in C# casting is more often done as object.ToInt()

So, in review, you have a bug in your JavaScript.

Upvotes: 3

Related Questions