Inverting a binary value of a number

天大地大妈咪最大 提交于 2019-12-04 07:21:24

MooGoo's answer is correct.

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/>");

You need to use a bitmask.

(~793 & 0x3ff).toString(2) //11100110

Or with XOR

793 ^ 0x3ff

You want to XOR the binary value with 111111111 - however many 1s as there are digits in the original. So:

var x = 793;
var result = x ^ parseInt((new Array(x.toString(2).length+1)).join("1"),2);

(Code for str_repeat taken from PHP.JS)

Revisiting years later, try:

var x = 793;
var result = parseInt(x.toString(2).replace(/[01]/g,function(n) {return 1-n;}),2);

I believe this will be more efficient... probably. Could be completely wrong. Oh well.

user11953136

I just do this

Let's say x = -11.3 and it's a 16 bit integer from somewhere.

My results will go into variable r.

var r = ((x & 0x7FFF) ^ 0x7FFF)+1;

It's the kiss principle.

Update

It's unclear to me whether you want a string of the inverted value, if so you can do this:

function invert(x){
    var e = x.toString(2).split('');
    for(var i = 0, l = e.length; i < l; i++) {
        e[i] = e[i] === '0' ? '1' : (e[i] === '1' ? '0' : e[i]);
    }
    return e.join('');
}
invert(793); // '0011100110'
invert(-793); // '-0011100110'

This will also preserve leading zeros.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!