Setting specific bits in a number

2019-05-17 12:13发布

问题:

var d = 7;

in binary: 7 = (111)

What I want to do is to set second place from right to 1 or 0 at disposal,

and return the decimal value.

For example,if I want to make the second 1 to 0,then after process should return a 5,

because 5=(101).

How to implement this in javascript?

EDIT

the answer should be something like this:

function func(decimal,n_from_right,zero_or_one)
{

}

Where decimal is the number to be processed, n_from_right is how many bits from right,in my example above it's 2. zero_or_one means to set that specific bit to 0 or 1 at disposal.

回答1:

The easiest way to clear a bit, is to use the and operation with it's bit complement.

7 =  0000000000000111
~2 = 1111111111111101
& :  0000000000000101

In code:

var d = 7, mask = 2;
d &= ~mask;

To set a bit instead of clearing it, you use the or operator instead:

d |= mask;

If you need to create the mask dynamically to handle different bits, you start with the value one (binary 0000000000000001) and shift the bit to the correct index. The second bit has index one (the rightmost bit has index zero), so:

var index = 1;
var mask = 1 << index;


回答2:

One way to do it, but you'd probably be better using bitwise operators

var d = 7;
var binary = d.toString(2);

binary = binary.split('');
binary[1] = "0";
binary = binary.join('');
binary = parseInt(binary,2);


回答3:

To set the second bit, simply OR with 2 (10 in binary)

var d=5;
var mask=2;
var second_bit_set=d | mask;


          d: 101
       mask: 010
 --------------------
 bitwise OR: 111

To remove the second bit, you want to AND with a value which has all bits set, apart from the second one. An easy way to construct this value is to perform bitwise NOT on the value, e.g. ~2

var d=7;
var mask=~2;
var second_bit_unset=d & mask;

           d: 111
        mask: 101
 --------------------
 bitwise AND: 101

See this bitwise operator reference for more information on these operators.



回答4:

/** Convert a decimal number to binary **/

var toBinary = function(decNum){
    return parseInt(decNum,10).toString(2);
}

/** Convert a binary number to decimal **/

var toDecimal = function(binary) {
    return parseInt(binary,2).toString(10);
}


回答5:

try using bitshifting:

d &~(1<<1)

see also this docs



回答6:

You can use the Javascript bitwise operators:

var five = 7 & ~2;

2 = 10 in binary



回答7:

var str="XXX\tYYYYYYY\n";
for(var i=0;i<=7;i++){
str+=(i+8).toString(2).substring(1)+"\t"+(i*11+22+128).toString(2).substring(1);
str+="\n";
}
console.info(str);

you can make a func from my bike