469,352 Members | 1,768 Online

# Bittest in Javascript?

I need a Javascript function that can do a Bit Test on a numeric
value. IOW, given a numeric value (a 16 bit integer value) and a bit
number, tell me whether that bit is 1 or 0.

I have no idea how to do this.

Help?
Jan 1 '06 #1
3 2836 Martin <ma**********@comcast.net> writes:
I need a Javascript function that can do a Bit Test on a numeric
value. IOW, given a numeric value (a 16 bit integer value) and a bit
number, tell me whether that bit is 1 or 0.

Since Javascript doesn't have a 16 bit integer type, you will just
have your value in the range 0..65535 in a number value. Bit
operations in Javascript will convert their operand to a 32 bit
integer before operating, so there is plenty of room for your numbers.

To test that the n'th bit is set, you use a mask with only the n'th
bit set. One such can be created using the left shift operator:

var mask = 1 << n;

Then you do a binary "and" on the number and the mask, to make sure
all other bits are nulled. If the result is non-null (and equal to the
mask) then the n'th bit was set in the original number.

var bitIsSet = (number & mask) != 0;

In total, a function to test a single bit:

function bitIsSet(number, bitnum) {
return (number & (1 << bitnum)) != 0;
}

Good luck
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jan 1 '06 #2
Martin wrote:
I need a Javascript function that can do a Bit Test on a numeric
value. IOW, given a numeric value (a 16 bit integer value) and a
bit number, tell me whether that bit is 1 or 0.

I have no idea how to do this.

Use the Bitwise AND operator `&', and the Bitwise Shift Left operator `<<':

if (n & (1 << b))
{
/*
* b-th bit of n if n is converted to a 32-bit integer,
* the least significant bit of n being the zeroth one
*/
}

Is this for class? Because it really is programming basics -- RTFM.

<URL:http://jibbering.com/faq/#FAQ3>
PointedEars
Jan 1 '06 #3
JRS: In article <ig********************************@4ax.com>, dated
Sun, 1 Jan 2006 13:44:53 local, seen in news:comp.lang.javascript,
Martin <ma**********@comcast.net> posted :
I need a Javascript function that can do a Bit Test on a numeric
value. IOW, given a numeric value (a 16 bit integer value) and a bit
number, tell me whether that bit is 1 or 0.

For reasonable values, N >> X & 1 returns the value of bit X of the
integer N.

--
 reply views Thread by ioana budai | last post: by 1 post views Thread by CARIGAR | last post: by reply views Thread by zhoujie | last post: by reply views Thread by goatbishop | last post: by 2 posts views Thread by mgbsher | last post: by reply views Thread by NeoPa | last post: by reply views Thread by dDule | last post: by 11 posts views Thread by ACB64 | last post: by 1 post views Thread by Darius9023 | last post: by