13,194,103 members (49,650 online)
alternative version

Stats

663.6K views
385 bookmarked
Posted 8 May 2002

An introduction to bitwise operators

, 8 May 2002
 Rate this:

Introduction

I have noticed that some people seem to have problems with bitwise operators, so I decided to write this brief tutorial on how to use them.

An Introduction to bits

Bits, what are they you may ask?

Well, simply put, bits are the individual ones and zeros that make up every thing we do with computers. All the data you use is stored in your computer using bits. A BYTE is made up of eight bits, a WORD is two BYTEs, or sixteen bits. And a DWORD is two WORDS, or thirty two bits.

``` 0 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 1 1 1 0 0 0
||              |               |               |              ||
|+- bit 31      |               |               |       bit 0 -+|
|               |               |               |               |
+-- BYTE 3 -----+--- BYTE 2 ----+--- BYTE 1 ----+-- BYTE 0 -----+
|                               |                               |
+----------- WORD 1 ------------+----------- WORD 0 ------------+
|                                                               |
+--------------------------- DWORD -----------------------------+```

The beauty of having bitwise operators is that you can use a BYTE, WORD or DWORD as a small array or structure. Using bitwise operators you can check or set the values of individual bits or even a group of bits.

Hexadecimal numbers and how they relate to bits

When working with bits, it is kind of hard to express every number using just ones and zeros, which is known as binary notation. To get around this we use hexadecimal (base 16) numbers.

As you may or may not know, it takes four bits to cover all the numbers from zero to fifteen, which also happens to be the range of a single digit hexadecimal number. This group of four bits, or half a BYTE, is called a nibble. As there are two nibbles in a BYTE, we can use two hexadecimal digits to show the value of one BYTE.

```NIBBLE   HEX VALUE
======   =========
0000        0
0001        1
0010        2
0011        3
0100        4
0101        5
0110        6
0111        7
1000        8
1001        9
1010        A
1011        B
1100        C
1101        D
1110        E
1111        F```

So if we had one BYTE containing the letter 'r' (ASCII code 114) it would look like this:

```0111 0010    binary

We could write it as '0x72'

Bitwise operators

There are six bitwise operators. They are:
&   The AND operator
|   The OR operator
^   The XOR operator
~   The Ones Complement or Inversion operator
>>   The Right Shift operator
<<   The Left Shift operator.

The & operator

The & (AND) operator compares two values, and returns a value that has its bits set if, and only if, the two values being compared both have their corresponding bits set. The bits are compared using the following table

```1   &   1   ==   1
1   &   0   ==   0
0   &   1   ==   0
0   &   0   ==   0
```

An ideal use for this is to set up a mask to check the values of certain bits. Say we have a BYTE that contains some bit flags, and we want to check if bit four bit is set.

```BYTE b = 50;
if ( b & 0x10 )
cout << "Bit four is set" << endl;
else
cout << "Bit four is clear" << endl;```

This would result in the following calculation

```  00110010  - b
& 00010000  - & 0x10
----------
00010000  - result
```

So we see that bit four is set.

The | operator

The | (OR) operator compares two values, and returns a value that has its bits set if one or the other values, or both, have their corresponding bits set. The bits are compared using the following table

```1   |   1   ==   1
1   |   0   ==   1
0   |   1   ==   1
0   |   0   ==   0
```

An ideal use for this is to ensure that certain bits are set. Say we want to ensure that bit three of some value is set

```BYTE b = 50;
BYTE c = b | 0x04;
cout << "c = " << c << endl;```

This would result in the following calculation

```  00110010  - b
| 00000100  - | 0x04
----------
00110110  - result
```

The ^ operator

The ^ (XOR) operator compares two values, and returns a value that has its bits set if one or the other value has its corresponding bits set, but not both. The bits are compared using the following table

```1   ^   1   ==   0
1   ^   0   ==   1
0   ^   1   ==   1
0   ^   0   ==   0
```

An ideal use for this is to toggle certain bits. Say we want toggle the bits three and four

```BYTE b = 50;
cout << "b = " << b << endl;
b = b ^ 0x18;
cout << "b = " << b << endl;
b = b ^ 0x18;
cout << "b = " << b << endl;```

This would result in the following calculations

```  00110010  - b
^ 00011000  - ^ 0x18
----------
00101010  - result

00101010  - b
^ 00011000  - ^ 0x18
----------
00110010  - result
```

The ~ operator

The ~ (Ones Complement or inversion) operator acts only on one value and it inverts it, turning all the ones int zeros, and all the zeros into ones. An ideal use of this would be to set certain bytes to zero, and ensuring all other bytes are set to one, regardless of the size of the data. Say we want to set all the bits to one except bits zero and one

```BYTE b = ~0x03;
cout << "b = " << b << endl;
WORD w = ~0x03;
cout << "w = " << w << endl;```

This would result in the following calculations

```00000011  - 0x03
11111100  - ~0x03  b

0000000000000011  - 0x03
1111111111111100  - ~0x03  w
```

Another ideal use, is to combine it with the & operator to ensure that certain bits are set to zero. Say we want to clear bit four

```BYTE b = 50;
cout << "b = " << b << endl;
BYTE c = b & ~0x10;
cout << "c = " << c << endl;```

This would result in the following calculations

```  00110010  - b
& 11101111  - ~0x10
----------
00100010  - result
```

The >> and << operators

The >> (Right shift) and << (left shift) operators move the bits the number of bit positions specified. The >> operator shifts the bits from the high bit to the low bit. The << operator shifts the bits from the low bit to the high bit. One use for these operators is to align the bits for whatever reason (check out the MAKEWPARAM, HIWORD, and LOWORD macros)

```BYTE b = 12;
cout << "b = " << b << endl;
BYTE c = b << 2;
cout << "c = " << c << endl;
c = b >> 2;
cout << "c = " << c << endl;```

This would result in the following calculations

```00001100  - b
00110000  - b << 2
00000011  - b >> 2
```

Bit Fields

Another interesting thing that can be done using bits is to have bit fields. With bit fields you can set up minature structures within a BYTE, WORD or DWORD. Say, for example, we want to keep track of dates, but we want to use the least amount of memory as possible. We could declare our structure this way

```struct date_struct {
BYTE day   : 5,   // 1 to 31
month : 4,   // 1 to 12
year  : 14;  // 0 to 9999
} date;```

In this example, the day field takes up the lowest 5 bits, month the next four, and year the next 14 bits. So we can store the date structure in twenty three bits, which is contained in three BYTEs. The twenty fourth bit is ignored. If I had declared it using an integer for each field, the structure would have taken up 12 BYTEs.

```|0 0 0 0 0 0 0 0|0 0 0 0 0 0 0 0|0 0 0 0 0 0 0 0|
|                           |       |         |
+------ year ---------------+ month +-- day --+```

Now lets pick this declaration apart to see what we are doing.

First we will look at the data type we are using for the bit field structure. In this case we used a BYTE. A BYTE is 8 bits, and by using it, the compiler will allocate one BYTE for storage. If however, we use more than 8 bits in our structure, the compiler will allocate another BYTE, as many BYTEs as it takes to hold our structure. If we had used a WORD or DWORD, the compiler would have allocated a total of 32 bits to hold our structure.

Now lets look at how the various fields are declared. First we have the variable (day, month, and year), followed by a colon that separates the variable from the number of bits that it contains. Each bit field is separated by a comma, and the list is ended with a semicolon.

Now we get to the struct declaration. We put the bit fields into a struct like this so that we can use convention structure accessing notation to get at the structure members. Also, since we can not get the addresses of bit fields, we can now use the address of the structure.

```date.day = 12;

dateptr = &date;
dateptr->year = 1852;```

Share

No Biography provided

You may also be interested in...

 First PrevNext
 A handy tool to see bitwise calculations in action Member 1133912313-May-15 10:04 Member 11339123 13-May-15 10:04
 Check out the BitwiseCmd app. Basically it's a online bitwise calculator that does basic bitwise operations (as implemented in JavaScript engine) which in many cases are similar to those described in this article. It arranges number in a convenient manner so you the bits neatly arranged one below the other. It has really helped me in learning of bitwise operators. Hope it will be of use to you also.
 ERROR Atul Khanduri16-Feb-14 15:27 Atul Khanduri 16-Feb-14 15:27
 Nice article.... Atul Khanduri30-Dec-13 3:14 Atul Khanduri 30-Dec-13 3:14
 My vote of 5 Aris794-Nov-13 6:30 Aris79 4-Nov-13 6:30
 My vote of 5 Member 97830185-Feb-13 10:41 Member 9783018 5-Feb-13 10:41
 Useful Topic duccuongpx22-Jun-12 8:47 duccuongpx 22-Jun-12 8:47
 My vote of 4 wangxj_nemo16-May-12 18:14 wangxj_nemo 16-May-12 18:14
 My vote of 4 yogesh muchhal23-Nov-11 17:33 yogesh muchhal 23-Nov-11 17:33
 My vote of 5 kamiccolo1-Jun-11 5:04 kamiccolo 1-Jun-11 5:04
 My vote of 4 VitStepanek1-Aug-10 21:02 VitStepanek 1-Aug-10 21:02
 Excellant, Very down to earth and insighful Member 84991028-Jul-10 5:05 Member 849910 28-Jul-10 5:05
 thank you Member 30784148-May-10 2:00 Member 3078414 8-May-10 2:00
 bitwise with floating point numbers Roman Tarasov1-Dec-09 2:33 Roman Tarasov 1-Dec-09 2:33
 Re: bitwise with floating point numbers PJ Arends4-Dec-09 5:52 PJ Arends 4-Dec-09 5:52
 useful article islandscape14-Oct-09 2:54 islandscape 14-Oct-09 2:54
 is here an error? langzhengyi31-May-09 20:53 langzhengyi 31-May-09 20:53
 Re: is here an error? spacevector10-Jul-12 21:13 spacevector 10-Jul-12 21:13
 Re: is here an error? Atul Khanduri16-Feb-14 15:19 Atul Khanduri 16-Feb-14 15:19
 Helpful article Ravi00326-Jan-09 23:10 Ravi003 26-Jan-09 23:10
 nice thanks moonbinary10-Jan-09 18:15 moonbinary 10-Jan-09 18:15
 good AlexanderBX3-Nov-08 18:58 AlexanderBX 3-Nov-08 18:58
 Nice work! Thank you ! cometdlut2-Oct-08 21:38 cometdlut 2-Oct-08 21:38
 Reading from file and adding values to array Srinivas3279 B19-Nov-07 23:27 Srinivas3279 B 19-Nov-07 23:27
 Convert back a shift operator wira1guys1-Oct-07 18:20 wira1guys 1-Oct-07 18:20
 Re: Convert back a shift operator PJ Arends2-Oct-07 5:55 PJ Arends 2-Oct-07 5:55
 Re: Convert back a shift operator [modified] wira1guys2-Oct-07 19:01 wira1guys 2-Oct-07 19:01
 Nice hxkolo7-Jun-07 0:10 hxkolo 7-Jun-07 0:10
 Extend my Knowledge... Shi Jun14-May-07 16:22 Shi Jun 14-May-07 16:22
 Good place to start brahmma17-Nov-06 20:47 brahmma 17-Nov-06 20:47
 Re: Good place to start ant-dog11-Jan-08 4:38 ant-dog 11-Jan-08 4:38
 Re: Good place to start xlyz.os31-Oct-09 20:47 xlyz.os 31-Oct-09 20:47
 Good LeeSharp15-Jun-06 5:37 LeeSharp 15-Jun-06 5:37
 Very Nice vijayakumar_akm10-May-05 17:15 vijayakumar_akm 10-May-05 17:15
 nice article ,u can add how bitwise ops can be combined Anonymous20-Sep-04 0:07 Anonymous 20-Sep-04 0:07
 Can i use the declaration? mahmutarik22-Mar-04 3:32 mahmutarik 22-Mar-04 3:32
 error C2034: 'year' : type of bit field too small for number of bits Lee McKenzie13-Mar-04 3:50 Lee McKenzie 13-Mar-04 3:50
 Re: error C2034: 'year' : type of bit field too small for number of bits leekillestein17-Jun-04 11:52 leekillestein 17-Jun-04 11:52
 Re: error C2034: 'year' : type of bit field too small for number of bits John R. Shaw14-May-07 18:49 John R. Shaw 14-May-07 18:49
 Re: error C2034: 'year' : type of bit field too small for number of bits islandscape14-Oct-09 3:03 islandscape 14-Oct-09 3:03
 Re: error C2034: 'year' : type of bit field too small for number of bits Atul Khanduri17-Feb-14 5:37 Atul Khanduri 17-Feb-14 5:37
 Nice Article saurabhbajaj27-Nov-03 22:17 saurabhbajaj 27-Nov-03 22:17
 TKS xhight2-Sep-03 8:16 xhight 2-Sep-03 8:16
 Re: TKS PJ Arends2-Sep-03 8:33 PJ Arends 2-Sep-03 8:33
 Great MessnerEW23-Jul-03 20:36 MessnerEW 23-Jul-03 20:36
 Re: Great manzoor1012-Dec-08 4:12 manzoor10 12-Dec-08 4:12
 Last Visit: 31-Dec-99 18:00     Last Update: 19-Oct-17 2:17 Refresh 123 Next »