1

I'm trying to convert some javascript code to c# code. At some point, in javascript, I have an expression like this:

var result = 8797569417216^909522486;

The result variable then contains the value 1849046582. I have heard that javascript uses 32bit numbers for bitwise operators, but I don't know how to use this information to get the same results in c#. When I ran the same line of code, result contains 8797942068790.

What I am missing?

1
  • Do you want the same result? The result you have is wrong - c# is giving the correct value... Commented Jan 7, 2016 at 15:06

2 Answers 2

3

You can convert the result to int:

var result = 8797569417216^909522486;
var realResult = unchecked((int) result);

Note the unchecked, because you value is clearly larger than an Int32.

Sign up to request clarification or add additional context in comments.

1 Comment

Addendum: just don't forget MAX_SAFE_INTEGER in JavaScript (9007199254740991), after this value result will differ because numbers in JS are stored in floating point.
0

The problem is that 8797942068790 cannot be represented with 32 bit, and thus C# handles it as 64-bit. You can however convert back (value-wise) to 32 bit using:

x & ((1L<<32)-1)

This works as follows. 1L means that you represent 1 using a 64 bit long. Next you shift it to the left by 32 places. This means that you obtain the value that is just higher than the maximum representable number with 32 bit. By subtracting 1, all 32 lowest bits are one, and all others zero, so: ((1L<<32)-1) is binary equal to:

00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111111

Now by using a bitwise &, you thus mask all values out that cannot be represented by 32 bit.

So for your example, this means:

csharp> (8797569417216^909522486)&((1L<<32)-1)
1849046582

(used the csharp interactive shell).

After that you can convert the result to an int, or an uint. An uint is unsigned, and so it is guaranteed that the value can be stored in an uint. An uint however, cannot work with negative numbers.

2 Comments

Masking is overkill in this case (though may be good to know) and you still have problem of converting long to int (but we don't know for sure if OP wants Int32 as result or not).
@Sinatr: in that case one can use an uint. I agree using unchecked is the best way. Nevertheless, it is useful to know how to use a few bithacks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.