按位移位 - 开始用C#.net不同的结果与PHP [英] Bitwise Shift - Getting different results in C#.net vs PHP

查看:199
本文介绍了按位移位 - 开始用C#.net不同的结果与PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行在PHP这个命令,我得到:

When I run this command in PHP, I get:

Code: 2269495617392648 >> 24
Result: 32

当我在C#.NET或vb.net运行它,我得到:

When I run it in C#.net or vb.net, I get:

Code: 2269495617392648 >> 24
Result: 135272480

PHP是正确的。

PHP is correct.

有趣的是,当我试图在.net中移比 INT32 的任何数字,它产生坏的结果。

The interesting thing is, that when I try to shift any number greater than int32 in .net, it yields bad results..

INT32(2147483647)产生从PHP和C#.NET相同的结果,在每个号码或vb.net

Every number under int32 (2147483647) yields the same results from php and c#.net or vb.net

有没有一种解决方法这.NET?

Is there a workaround for this in .net?

推荐答案

严格地说,PHP是错误的。

Strictly speaking, PHP is wrong.

数的整个位模式 2269495617392648 是:

1000 0001 0000 0001 1000 0010 0000 0001 1000 0001 0000 0000 1000 (2269495617392648)

右移这24次让你:

Right shifting this 24 times gets you:

0000 0000 0000 0000 0000 0000 1000 0001 0000 0001 1000 0010 0000 (135272480)

这是位模式 135272480 ,而不是 32

什么是显然事情在PHP是多少 2269495617392648 按perserving只有较低的被截断为 538447880 32位。请注意,数字 2269495617392648 是太大了,可安装在32位整数,带符号。

What's going on in PHP apparently is that the number 2269495617392648 is being truncated to 538447880 by perserving only the lower 32 bits. Note that the number 2269495617392648 is much too big to fit in a 32-bit integer, signed or unsigned.

右移截位24倍为我们提供了 32

Right shifting the truncated bits 24 times gives us 32.

Before truncation to 32-bits:
1000 0001 0000 0001 1000 0010 0000 0001 1000 0001 0000 0000 1000 (2269495617392648)

After truncation to 32-bits:
0010 0000 0001 1000 0001 0000 0000 1000 (538447880)

Right shifting the truncated bits by 24 bits:
0000 0000 0000 0000 0000 0000 0010 0000 (32)

当你说你已经提到了这个问题:

You have alluded to this problem when you said:

有趣的是,当我
  推诿任何数量大于
  INT32在.net中它产生不好的结果。

The interesting thing is, that when I try to shift any number greater then int32 in .net it yields bad results..

它给你不好的结果,因为一些位是为了适应32位被剁掉。

It gives you bad results because some bits are being chopped off in order to fit in 32 bits.

如果你从PHP移植到C#和需要preserve这种行为,你需要使用 2269495617392648&放手动截断位;为0xffffffff ,而不是仅仅 2269495617392648 (见<一href=\"http://stackoverflow.com/questions/6006574/bitwise-shift-getting-different-results-in-c-net-vs-php/6006589#6006589\">jcomeau_ictx's回答)。但要注意的是,对位截断在你的PHP code回事的问题。我不能肯定,如果是有意还是无意。

If you're porting from PHP to C# and need to preserve this behavior, you need to manually truncate the bits by using 2269495617392648 & 0xffffffff instead of just 2269495617392648 (see jcomeau_ictx's answer). But be aware that there is an issue of bit truncation going on in your PHP code. I'm not certain if it's intentional or not.

这篇关于按位移位 - 开始用C#.net不同的结果与PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆