本文介绍了如何在 javascript 中对超过 32 位的变量进行按位 AND 运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 javascript 中有 2 个数字,我想对其进行处理.它们都是 33 位长

I have 2 numbers in javascript that I want to bit and. They both are 33bit long

在 C# 中:

 ((4294967296 & 4294967296 )==0) is false

但在 javascript 中:

but in javascript:

 ((4294967296 & 4294967296 )==0) is true

4294967296 是 ((long)1) <<32

4294967296 is ((long)1) << 32

据我所知,这是因为 javascript 在执行位操作时将值转换为 int32.

As I understand it, it is due to the fact that javascript converts values to int32 when performing bit wise operations.

我该如何解决这个问题?关于如何替换位以及使用一组其他数学运算以不丢失位的任何建议?

How do I work around this?Any suggestions on how to replace bit and with a set of other math operations so that bits are not lost?

推荐答案

您可以将每个 vars 拆分为 2 个 32 位值(如高位字和低位字),然后对这两对进行按位运算.

You could split each of the vars into 2 32-bit values (like a high word and low word), then do a bitwise operation on both pairs.

以下脚本作为 Windows .js 脚本运行.您可以将 WScript.Echo() 替换为用于 Web 的 alert().

The script below runs as a Windows .js script. You can replace WScript.Echo() with alert() for Web.

var a = 4294967296;
var b = 4294967296;

var w = 4294967296; // 2^32

var aHI = a / w;
var aLO = a % w;
var bHI = b / w;
var bLO = b % w;

WScript.Echo((aHI & bHI) * w + (aLO & bLO));

这篇关于如何在 javascript 中对超过 32 位的变量进行按位 AND 运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 16:10
查看更多