spacer
Yehuda Shiran October 14, 1999
The Bitwise AND Operator
Tips: October 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

The bitwise AND operator compares two bits and assign 1 to the result only if both operands are 1. Here is the truth table for this operator:

Bit1Bit2Bit1 & Bit2
000
010
100
111

The AND operator, like all other bitwise operators, can take only numeric values as its operands. Since JavaScript does not support bit-length variables, you have to do your bitwise math with byte-length operands, i.e. with integers that are less than 256. Any operand longer than a byte (greater than 255) will be chopped and only the LSB (Least Significant Byte) will be used.

Let's do a simple calculation:

NameDecimalHexBinary
Op1350x2300100011
Op21140x7201110010
Op1 & Op2340x2200100010

You can use bitwise operands for many different tasks. The following function uses the bitwise AND operator to determine whether the number is odd or even. It returns a true value if decimalNumber is even, and a false value if it is odd:

function checkEven(decimalNumber) {
  return (decimalNumber & 1 == 0)
}


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business