我正在嘗試將 PHP 中的值按位移位,與 JavaScript 中的結(jié)果相比。我已經(jīng)嘗試過 stackoverflow 中的解決方案,但目前我無法讓它按照我想要的方式工作。我目前正在運行 PHP 7.1。例如在運行這個的 Chrome WebTools Console 等 JS 環(huán)境中var testValue = 94427771;(testValue << 5)結(jié)果是: -1273278624而在 PHP 中類似產(chǎn)生以下內(nèi)容:$testValue = 94427771;$testValue = ($testValue << 5);echo $testValue;輸出是: 96694037504我也試過這個在 stackOverflow 上發(fā)布的函數(shù)function shift_left_32( $a, $b ) { return ( $c = $a << $b ) && $c >= 4294967296 ? $c - 4294967296 : $c;}在哪里運行代碼shift_left_32($testValue, 5);它返回值:3021688672我怎么能去解決這個問題。謝謝你。
1 回答

慕田峪7331174
TA貢獻1828條經(jīng)驗 獲得超13個贊
如果您想將按位移位的返回值限制為 32 位有符號整數(shù),那么您可以做的是將數(shù)字取模為最大 32 位有符號整數(shù),然后將其溢出。
function shift_left_32( $a, $b ) {
return ( $c = $a << $b ) && $c > 0x7FFFFFFF ? ($c % 0x80000000)-0x80000000 : $c;
}
或更簡單和更正確的按位或:
function shift_left_32( $a, $b ):int {
return ( $a << $b ) | -0x80000000;
}
- 1 回答
- 0 關(guān)注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消