Reputation: 97
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
Reputation: 1339
You can't expect the same behavior on C# by default. Because:
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
Reputation: 543
So, there are a few things going on here.
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.
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
.
(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.
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