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.'