Although JavaScript does not support bit-fields, you can perform many binary operations on patterns of bits by using the bitwise operators and various simple mathematical expressions to simulate other bit manipulation operators that are not provided as part of the standard.

Op | Description |
---|---|

~ | Bitwise complement (NOT) |

& | Bitwise AND |

<< | Bitwise left shift |

>> | Bitwise right shift |

>>> | Bitwise right shift (unsigned) |

| | Bitwise inclusive OR |

^ | Bitwise XOR (exclusive OR) |

&= | Bitwise AND and assign to an LValue |

|= | Bitwise inclusive OR and assign to an LValue |

^= | Bitwise exclusive XOR and assign to an LValue |

<<= | Bitwise shift left and assign to an LValue |

>>= | Bitwise shift right and assign to an LValue |

>>>= | Bitwise shift right (unsigned) and assign to an LValue |

The bits are individually weighted according to their position relative to the least significant digit.

The single bit at the extreme right-hand end is defined by the integer value 1. The next significant bit is derived by using a zero-based indexing scheme to raise 2 to the power of its index position. Thus 2 raised to the power 0 is 1. The value 2 raised to the power 1 is 2 and thus the values proceed like this, moving from right to left:

1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 etc.

To build bit masks containing a set bit for several positions, simply add the component bit values together. Thus a mask that includes all the four least significant bits in a value is equal to:

1 + 2 + 4 + 8

Here are some other useful mask values (note that we only show 8 bit values here to demonstrate the concept):

Prev | Home | Next |

Bit | Up | Bitwise AND (&) |

JavaScript Programmer's Reference, Cliff WoottonWrox Press (www.wrox.com)Join the Wrox JavaScript forum at p2p.wrox.comPlease report problems to support@wrox.com© 2001 Wrox Press. All Rights Reserved. Terms and conditions. |