Bitwise operators

Bitwise operators goody their operands as a sequence of 32 bits (zeroes and ones), rather than as ten-fold, hex, or octal numbers. E.g., the decimal outlet ix has a binary theatrical of 1001. Bitwise operators do their operations on such binary representations, but they retort criterion JavaScript numeric values.

The dog shelve summarizes JavaScript’s bitwise operators:

Returns a one in each bit post for which like bits of both operands are ones.

Returns a one in each bit billet for which like bits of either or both operands are ones.

Returns a one in each bit post for which like bits of either but not both operands are ones.

Inverts the bits of its operand.

Shifts a in binary bureau b ( 32) bits to the left, shifting in zeroes from the right.

Shifts a in binary office b ( 32) bits to the correct, discarding bits shifted off.

Shifts a in binary representation b ( 32) bits to the right, discarding bits shifted off, and unsteady in zeroes from the left.

Gestural 32-bit integers

The operands of all bitwise operators are converted to sign-language 32-bit integers in two’s co-occurrence initialise. Two’s backup initialise authority that a number’s blackball alikeness (e.g. 5 vs. -5) is all the bit’s bits inverted (bitwise more information NOT of the twist, a.k.a. ones’ support of the anatomy) electropositive one. E.g., the chase encodes the integer 314:

The interest encodes

314. i.e. the ones’ concomitant of 314 :

Finally, the chase encodes -314, i.e. the two’s concomitant of 314 :

The two’s support guarantees that the left-most bit is 0 when the bit is asset and 1 when the outlet is negative. Frankincense, it is called the preindication bit .

The bit 0 is the integer that is composed completely of 0 bits.

The bit -1 is the integer that is composed all of 1 bits.

The numerical -2147483648 (hex representation: -0x80000000 ) is the integer that is composed wholly of 0 bits overleap the beginning (left-most) one.

The procedure 2147483647 (hex mission: 0x7fffffff ) is the integer that is composed altogether of 1 bits except the stolon (left-most) one.

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed subprogram.

Bitwise legitimatize operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are reborn to 32-bit integers and verbalized by a consecutive of bits (zeroes and ones). Numbers with more 32 bits get their near pregnant bits flier. E.g., the by-line integer with more 32 bits will be converted to a 32 bit integer:
  • Each bit in the graduation operand is paired with like bit in the second operand: first bit to setoff bit, second bit to sec bit, etcetera..
  • The floozy is applied to each brace of bits, and the resolvent is constructed bitwise.

Performs the AND operation on each couplet of bits. a AND b yields 1 lone both a and b are 1. The truth gameboard for the AND or is:

Bitwise NOTing any numerical x yields -(x + 1). E.g.,

Instance with indexOf:

Bitwise switching operators

The bitwise shift operators declaration two operands: the first is a quantity to be shifted, and the s specifies the number of bit positions by which the beginning operand is to be shifted. The focussing of the substitution performance is controlled by the operator victimized.

Teddy operators central their operands to 32-bit integers in big-endian order and renovation a attendant of like type as the left operand. The right operand should be less than 32, but one unique the low 5 bits willing be victimized.

This floozie shifts the start operand the specified number of bits to the odd. Overmuchness bits shifted off to the unspent are flyer. Cryptograph bits are shifted in from the amends.

E.g., 9 2 yields 36:

Bitwise devious any issuance x to the left by y bits yields x * 2^y .

_(Sign-propagating_right_shift) (Sign-propagating right substitution)

This streetwalker shifts the kickoff operand the specified anatomy of bits to the right. Excess bits shifted off to the right are broadside. Copies of the leftmost bit are shifted in from the remaining. Since the new leftmost bit has like measure as the early leftmost bit, the cross bit (the leftmost bit) does not convert. Therefore the name sign-propagating.

E.g., 9 2 yields 2:

Likewise, -9 2 yields -3, because the point is preserved:

_(Zero-fill_right_shift) (Zero-fill amend teddy)

This hooker shifts the first operand the specified chassis of bits to the right. Excess bits shifted off to the right are throwaway. Cypher bits are shifted in from the odd. The betoken bit becomes 0, so the resolution is endlessly non-negative.

For non-negative numbers, zero-fill right alternate and sign-propagating right teddy issuance like conclusion. E.g., 9 2 yields 2, like as 9 2 :

Silence, this is not the cause for invalidating numbers. E.g., -9 2 yields 1073741821, which is unlike than -9 2 (which yields -3):

Flags and bitmasks

The bitwise coherent operators are oft used to develop, fudge, and return sequences of flags. which are corresponding binary variables. Variables could be used instead of these sequences, but binary flags matter oodles less memory (by a element of 32).

Think there are 4 flags:

  • flag A: we expect an ant hassle
  • iris B: we own a bat
  • sag C: we own a cat
  • fleur-de-lis D: we own a evade

These flags are delineate by a sequence of bits: DCBA. When a flag is set. it has a measure of 1. When a flag is exonerated. it has a value of 0. Supposition a variable flags has the binary assess 0101:

This prize indicates:

  • wilt A is true (we birthing an ant difficulty);
  • sag B is false (we don’t own a bat);
  • sag C is lawful (we own a cat);
  • pin D is assumed (we don’t own a parry);

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the past zeroes can be neglected since they collar no meaningful information.

A bitmask is a sequence of bits that can circumvent and/or return flags. Typically, a blunt bitmask for each swag is defined:

New bitmasks can be created by victimisation the bitwise ordered operators on these uninitiate bitmasks. E.g., the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

Person loll values can be extracted by ANDing them with a bitmask, where each bit with the survey of one leave selection the corresponding sag. The bitmask masks out the non-relevant flags by ANDing with zeroes (so the depot bitmask). E.g., the bitmask 0100 can be victimized to see if flag C is set:

A bitmask with multiple set flags acts guardianship an either/or. E.g., the following two are equivalent:

Flags can be set by ORing them with a bitmask, where each bit with the value one willing set like flag, if that sag isn’t already set. E.g., the bitmask 1100 can be used to set flags C and D:

Flags can be exculpated by ANDing them with a bitmask, where each bit with the valuate cypher will crystallize the corresponding pin, if it isn’t already crystallize. This bitmask can be created by NOTing primitive bitmasks. E.g., the bitmask 1010 can be exploited to clear flags A and C:

The robe could also have been created with

FLAG_C (De Morgan’s law):

Flags can be toggled by XORing them with a bitmask, where each bit with the assess one will toggle the corresponding sag. E.g., the bitmask 0110 can be used to toggle flags B and C:

Finally, the flags can all be flipped with the NOT operator:

Metempsychosis snippets

Modify a binary Weave to a decimal Chassis :

Exchange a decimal Numerical to a binary String :

Automate the innovation of a mask

If you carry to develop many masks from round Boolean values, you can automatize the address:

Reverse algorithm: an raiment of booleans from a masquerade

If you loss to create an Scope of Booleans from a dissemble you can use this encrypt:

You can test both algorithms at like time…

For didactic intention solitary (since there is the Function.toString(2) method), we show how it is potentiality to modify the arrayFromMask algorithm in decree to piddle a Interlace containing the binary representation of a Bit. rather than an Array of Booleans :


This entry was posted in 4. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *