在一些设置的特定位 [英] Setting specific bits in a number

查看:119
本文介绍了在一些设置的特定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变种D = 7;

在二进制:7 =(111)

in binary: 7 = (111)

我想要做的是正确的,从第二个地方在处置设置为1或0,

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

和返回的十进制值。

例如,如果我想让第二个是1比0,那么处理后应该返回5,

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

由于5 =(101)。

because 5=(101).

如何实现这在JavaScript?

How to implement this in javascript?

修改

答案应该是这样的:

function func(decimal,n_from_right,zero_or_one)
{

}

其中小数要处理的数量,
n_from_right是怎么从右多少位,我在上面的例子是2。
zero_or_one意味着该特定位设置为0或1在处置

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.

推荐答案

要清除位的最简单方法,是使用和操作它的补码。

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

7 =  0000000000000111
~2 = 1111111111111101
& :  0000000000000101

在code:

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

要设置位,而不是清除它,使用或操作来代替:

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

d |= mask;

如果您需要动态地创建蒙版来处理不同的位,你开始值一(二进制0000000000000001)和位转移到正确的索引。第二位的索引是一个(最右边位的索引值为零),所以:

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;

这篇关于在一些设置的特定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆