Setting specific bits to a number

var d = 7;

in binary format: 7 = (111)

What I want to do is set the second place on the right to 1 or 0,

and return the decimal value.

For example, if I want to make the second one from 1 to 0, then after the process should return 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)
{

}

If the decimal number is the number to be processed, n_from_right is the number of bits to the right, in my example above 2. 2. zero_or_one means that this particular bit is set to 0 or 1.

+3
source share
7 answers

The easiest way to clear a bit is to use and refine the bit with it.

7 =  0000000000000111
~2 = 1111111111111101
& :  0000000000000101

In code:

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

, :

d |= mask;

, , ( 0000000000000001) . ( ), :

var index = 1;
var mask = 1 << index;
+14

, , ,

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

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

, OR 2 (10 )

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


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

, , , . NOT , . ~ 2

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

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

. .

+1
source

/ ** Convert decimal to binary ** /

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

/ ** Convert binary to decimal ** /

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

try using bitgifting:

d &~(1<<1)

see also these documents

0
source

You can use bitwise Javascript operators :

var five = 7 & ~2;

2 = 10 in binary format

0
source
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 create func from my bike

0
source

Source: https://habr.com/ru/post/1718263/


All Articles