What are bitwise operators?
Asked Answered
C

9

135

I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me.

I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D

Just a few more questions - what are some practical applications of bitwise operations? When might you use them?

Carolanncarole answered 9/11, 2008 at 23:59 Comment(1)
For further questions, you might want to add a new SO question and reference this one. You'll probably get a better set of answers that way.Infliction
M
186

Since nobody has broached the subject of why these are useful:

I use bitwise operations a lot when working with flags. For example, if you want to pass a series of flags to an operation (say, File.Open(), with Read mode and Write mode both enabled), you could pass them as a single value. This is accomplished by assigning each possible flag it's own bit in a bitset (byte, short, int, or long). For example:

 Read: 00000001
Write: 00000010

So if you want to pass read AND write, you would pass (READ | WRITE) which then combines the two into

00000011

Which then can be decrypted on the other end like:

if ((flag & Read) != 0) { //...

which checks

00000011 &
00000001

which returns

00000001

which is not 0, so the flag does specify READ.

You can use XOR to toggle various bits. I've used this when using a flag to specify directional inputs (Up, Down, Left, Right). For example, if a sprite is moving horizontally, and I want it to turn around:

     Up: 00000001
   Down: 00000010
   Left: 00000100
  Right: 00001000
Current: 00000100

I simply XOR the current value with (LEFT | RIGHT) which will turn LEFT off and RIGHT on, in this case.

Bit Shifting is useful in several cases.

x << y

is the same as

x * 2y

if you need to quickly multiply by a power of two, but watch out for shifting a 1-bit into the top bit - this makes the number negative unless it's unsigned. It's also useful when dealing with different sizes of data. For example, reading an integer from four bytes:

int val = (A << 24) | (B << 16) | (C << 8) | D;

Assuming that A is the most-significant byte and D the least. It would end up as:

A = 01000000
B = 00000101
C = 00101011
D = 11100011
val = 01000000 00000101 00101011 11100011

Colors are often stored this way (with the most significant byte either ignored or used as Alpha):

A = 255 = 11111111
R = 21 = 00010101
G = 255 = 11111111
B = 0 = 00000000
Color = 11111111 00010101 11111111 00000000

To find the values again, just shift the bits to the right until it's at the bottom, then mask off the remaining higher-order bits:

Int Alpha = Color >> 24
Int Red = Color >> 16 & 0xFF
Int Green = Color >> 8 & 0xFF
Int Blue = Color & 0xFF

0xFF is the same as 11111111. So essentially, for Red, you would be doing this:

Color >> 16 = (filled in 00000000 00000000)11111111 00010101  (removed 11111111 00000000)
00000000 00000000 11111111 00010101 &
00000000 00000000 00000000 11111111 =
00000000 00000000 00000000 00010101 (The original value)
Monochloride answered 10/11, 2008 at 0:39 Comment(2)
x<<n , so n must be in the form of 2^value?Satanism
Remember also: xor operator is a reversible operation (a^b)^b==aCoeducation
I
31

It is worth noting that the single-bit truth tables listed as other answers work on only one or two input bits at a time. What happens when you use integers, such as:

int x = 5 & 6;

The answer lies in the binary expansion of each input:

  5 = 0 0 0 0 0 1 0 1
& 6 = 0 0 0 0 0 1 1 0
---------------------
      0 0 0 0 0 1 0 0

Each pair of bits in each column is run through the "AND" function to give the corresponding output bit on the bottom line. So the answer to the above expression is 4. The CPU has done (in this example) 8 separate "AND" operations in parallel, one for each column.

I mention this because I still remember having this "AHA!" moment when I learned about this many years ago.

Infliction answered 10/11, 2008 at 0:11 Comment(2)
Wow, that makes a lot more sense now. It sounded a lot more complicated than it apparently is. Thanks. I'm not sure which to choose as the right answer as there are loads of good ones, and I can't upvote so.. thanksCarolanncarole
been working w this for a while, without knowing that. thanksImpatiens
H
28

Bitwise operators are operators that work on a bit at a time.

AND is 1 only if both of its inputs are 1.

OR is 1 if one or more of its inputs are 1.

XOR is 1 only if exactly one of its inputs are 1.

NOT is 1 only if its input are 0.

These can be best described as truth tables. Inputs possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the two inputs.

AND|0 1      OR|0 1
---+----    ---+----
  0|0 0       0|0 1
  1|0 1       1|1 1

XOR|0 1     NOT|0 1
---+----    ---+---
  0|0 1        |1 0
  1|1 0

One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:

    203: 1100 1011
AND  15: 0000 1111
------------------
 IS  11: 0000 1011
Hildebrandt answered 10/11, 2008 at 0:4 Comment(0)
E
18

These are the bitwise operators, all supported in JavaScript:

  • op1 & op2 -- The AND operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.

  • op1 | op2 -- The OR operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.

  • op1 ^ op2 -- The EXCLUSIVE-OR operator compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.

  • ~op1 -- The COMPLEMENT operator is used to invert all of the bits of the operand.

  • op1 << op2 -- The SHIFT LEFT operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.

  • op1 >> op2 -- The SHIFT RIGHT operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is preserved.

  • op1 >>> op2 -- The SHIFT RIGHT - ZERO FILL operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half. The left-most sign bit is discarded.

Edwyna answered 10/11, 2008 at 0:3 Comment(3)
"if the bits are complementary" - waht?Encipher
@AndreyTyukin two bits are complementary if one of them is 1 and the other is 0.Edwyna
@JeffHillman According to your description in the comment, 1 and 1 are not "complementary". Then it's unclear to me why 1 | 1 gives 1 and not 0, and how | is then supposed to be different from ^. I had to use this Q/A as a duplicate target few days ago, and I wished that after 10 years one would have a clearer canonical duplicate for this kind of questions.Encipher
H
4

To break it down a bit more, it has a lot to do with the binary representation of the value in question.

For example (in decimal):
x = 8
y = 1

would come out to (in binary):
x = 1000
y = 0001

From there, you can do computational operations such as 'and' or 'or'; in this case:
x | y = 
1000 
0001 |
------
1001

or...9 in decimal

Hope this helps.

Helman answered 10/11, 2008 at 0:14 Comment(2)
| is an OR operations?Holiday
For some reason this made the most sense to me. Still not sure about the x | y = 1000 0001 | part thoughForme
R
4

In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations.

operations:

  • bitwise AND

  • bitwise OR

  • bitwise NOT

  • bitwise XOR

  • etc

List item

    AND|0 1        OR|0 1 
    ---+----      ---+---- 
      0|0 0         0|0 1 
      1|0 1         1|1 1 

   XOR|0 1        NOT|0 1 
   ---+----       ---+--- 
     0|0 1           |1 0 
     1|1 0

Eg.

    203: 1100 1011
AND  15: 0000 1111
------------------
  =  11: 0000 1011

Uses of bitwise operator

  • The left-shift and right-shift operators are equivalent to multiplication and division by x * 2y respectively.

Eg.

int main()
{
     int x = 19;
     printf ("x << 1 = %d\n" , x <<1);
     printf ("x >> 1 = %d\n", x >>1);
     return 0;
}
// Output: 38 9
  • The & operator can be used to quickly check if a number is odd or even

Eg.

int main()
{
    int x = 19;
    (x & 1)? printf("Odd"): printf("Even");
    return 0;
 }
// Output: Odd
  • Quick find minimum of x and y without if else statement

Eg.

int min(int x, int y)
{
    return y ^ ((x ^ y) & - (x < y))
}
  • Decimal to binary conversion

Eg.

#include <stdio.h>
int main ()
{
    int n , c , k ;
    printf("Enter an integer in decimal number system\n " ) ;
    scanf( "%d" , & n );
    printf("%d in binary number
    system is: \n " , n ) ;
    for ( c = 31; c >= 0 ; c -- )
    {
         k = n >> c ;
         if ( k & 1 )
              printf("1" ) ;
         else
              printf("0" ) ;
      }
      printf(" \n " );
      return 0 ;
}
  • The XOR gate encryption is popular technique, because of its complixblity and reare use by the programmer.
  • bitwise XOR operator is the most useful operator from technical interview perspective.

bitwise shifting works only with +ve number

Also there is a wide range of use of bitwise logic

Radical answered 21/4, 2016 at 7:2 Comment(3)
"complixblity and reare..." ?Harvin
The left-shift and right-shift operators are equivalent to multiplication and division by x * 2y respectively. That's right! muyiy.cn/question/program/102.htmlTwosome
my solution repl.it/@xgqfrms/…Twosome
P
3

When the term "bitwise" is mentioned, it is sometimes clarifying that is is not a "logical" operator.

For example in JavaScript, bitwise operators treat their operands as a sequence of 32 bits (zeros and ones); meanwhile, logical operators are typically used with Boolean (logical) values but can work with non-Boolean types.

Take expr1 && expr2 for example.

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

a = "Cat" && "Dog"     // t && t returns Dog
a = 2 && 4     // t && t returns 4

As others have noted, 2 & 4 is a bitwise AND, so it will return 0.

You can copy the following to test.html or something and test:

<html>
<body>
<script>
    alert("\"Cat\" && \"Dog\" = " + ("Cat" && "Dog") + "\n"
        + "2 && 4 = " + (2 && 4) + "\n"
        + "2 & 4 = " + (2 & 4));
</script>
Powel answered 10/11, 2008 at 0:26 Comment(0)
D
0

It might help to think of it this way. This is how AND (&) works:

It basically says are both of these numbers ones, so if you have two numbers 5 and 3 they will be converted into binary and the computer will think

         5: 00000101
         3: 00000011

are both one: 00000001 0 is false, 1 is true

So the AND of 5 and 3 is one. The OR (|) operator does the same thing except only one of the numbers must be one to output 1, not both.

Defrayal answered 20/6, 2014 at 14:30 Comment(0)
M
-5

I kept hearing about how slow JavaScript bitwise operators were. I did some tests for my latest blog post and found out they were 40% to 80% faster than the arithmetic alternative in several tests. Perhaps they used to be slow. In modern browsers, I love them.

I have one case in my code that will be faster and easier to read because of this. I'll keep my eyes open for more.

Miseno answered 10/2, 2009 at 0:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.