omg
omg

Reputation: 139872

Setting specific bits in a number

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.

Upvotes: 3

Views: 11084

Answers (7)

Dipesh KC
Dipesh KC

Reputation: 3297

/** 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);
}

Upvotes: 1

KOLANICH
KOLANICH

Reputation: 3072

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

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300855

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.

Upvotes: 1

Guffa
Guffa

Reputation: 700362

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;

Upvotes: 16

Greg
Greg

Reputation: 321648

You can use the Javascript bitwise operators:

var five = 7 & ~2;

2 = 10 in binary

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125488

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

Upvotes: 11

tliff
tliff

Reputation: 1764

try using bitshifting:

d &~(1<<1)

see also this docs

Upvotes: 0

Related Questions