views:

361

answers:

5

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.

A: 

try using bitshifting:

d &~(1<<1)

see also this docs

tliff
+1  A: 

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);
Russ Cam
I agree bitwise arithmetic is best, but +1 for pointing out the relatively little-known way to convert to/from binary strings.
bobince
A: 

You can use the Javascript bitwise operators:

var five = 7 & ~2;

2 = 10 in binary

Greg
What does ~2 mean?
Shore
~ is bitwise NOT - https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Bitwise_Operators#.7e_%28Bitwise_NOT%29
Paul Dixon
+3  A: 

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;
Guffa
+1 - great answer, well explained
Russ Cam
A: 

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.

Paul Dixon