反转数字的二进制值 [英] Inverting a binary value of a number
问题描述
我想先将数字转换为二进制,然后按位反转.像这样:
I would like first to convert a number to binary, then invert it bitwise. Like this:
数字是793 = 1100011001
然后将二进制值转换为: 0011100110
Number is 793 = 1100011001
then convert the binary value into: 0011100110
在JavaScript中,我可以执行以下操作:
In JavaScript I can do the following:
var x = 793;
document.write(x.toString(2)); // gives 0011100110
这将给我数字的二进制值.但是如何将二进制按位反转?
This will give me the binary value of the number. But how do I invert the binary bitwise?
我尝试了〜
运算符,但可能无法正常工作.输出为: -1100011010
I tried the ~
operator, but not working probably. The output is: -1100011010
推荐答案
MooGoo的答案正确.
MooGoo's answer is correct.
以下是有关正在发生的事情的信息....让我们假设这是一个64位整数.
Here is some information about what is happening.... Lets assume this is a 64 bit integer.
793 = 1100011001
~793 = -794 = 1111111111111111111111111111111111111111111111111111110011100110
0x3ff = 1111111111
(-793 & 0x3ff) = 11100110
因此,您可以使用以下代码来解决所有情况:
So you could do this to solve for all cases with this code:
var x = 793; // input value
var y = x.toString(2);
var yl = y.length;
var mask = (Math.pow(2,yl)-1); // calculate mask
var result = ~x & mask;
document.write(result.toString(2)+"<br/>");
这篇关于反转数字的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!