简体   繁体   English

如何在c#和javascript中使xor结果相等

[英]How to make xor result equal in c# and javascript

I'm trying to convert some javascript code to c# code. 我正在尝试将一些javascript代码转换为c#代码。 At some point, in javascript, I have an expression like this: 在某些时候,在javascript中,我有一个这样的表达式:

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#. 然后结果变量包含值1849046582.我听说javascript使用32位数字作为按位运算符,但我不知道如何使用这些信息在c#中获得相同的结果。 When I ran the same line of code, result contains 8797942068790. 当我运行相同的代码行时,结果包含8797942068790。

What I am missing? 我错过了什么?

You can convert the result to int : 您可以将结果转换为int

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

Note the unchecked, because you value is clearly larger than an Int32. 请注意未选中,因为您的值明显大于Int32。

The problem is that 8797942068790 cannot be represented with 32 bit, and thus C# handles it as 64-bit. 问题是8797942068790不能用32位表示,因此C#将其处理为64位。 You can however convert back (value-wise) to 32 bit using: 但是,您可以使用以下命令将(按值)转换回32位:

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

This works as follows. 其工作原理如下。 1L means that you represent 1 using a 64 bit long . 1L表示使用64位long表示1 Next you shift it to the left by 32 places. 接下来,将它向左移动32个位置。 This means that you obtain the value that is just higher than the maximum representable number with 32 bit. 这意味着您获得的值远远高于32位的最大可表示数字。 By subtracting 1 , all 32 lowest bits are one, and all others zero, so: ((1L<<32)-1) is binary equal to: 通过减1 ,所有32个最低位都是1,所有其他位数为零,因此: ((1L<<32)-1)二进制等于:

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. 现在,通过使用按位& ,您可以屏蔽无法用32位表示的所有值。

So for your example, this means: 所以对于你的例子,这意味着:

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

(used the csharp interactive shell). (使用了csharp交互式shell)。

After that you can convert the result to an int , or an uint . 之后,您可以将结果转换为intuint An uint is unsigned, and so it is guaranteed that the value can be stored in an uint . uint是无符号的,因此可以保证该值可以存储在uint An uint however, cannot work with negative numbers. 但是, uint不能与负数一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM