Click here to Skip to main content
Click here to Skip to main content

An introduction to bitwise operators

, 8 May 2002 CPOL
Rate this:
Please Sign up or sign in to vote.
This article gives a brief overview of C style bitwise operators

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
  7    2     hexadecimal

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;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

PJ Arends
President
Canada Canada
No Biography provided

Comments and Discussions

 
GeneralRe: A minor correction... PinmemberPJ Arends13-Jun-02 14:18 
GeneralThanks...... PinmemberMazdak23-May-02 21:52 
GeneralRe: Thanks...... PinmemberPJ Arends24-May-02 6:23 
GeneralRe: Thanks...... PinmemberMazdak24-May-02 8:42 
GeneralRe: Thanks...... PinmemberTim Smith24-May-02 8:52 
GeneralRe: Thanks...... PinmemberMazdak24-May-02 19:07 
GeneralGreat but.... Pinmemberjohny quest19-May-02 18:16 
GeneralRe: Great but.... PinmemberPJ Arends20-May-02 7:44 
GeneralDate_struct PinmemberKarstenK13-May-02 20:41 
GeneralValuable article!! PinmemberWREY12-May-02 10:03 
GeneralGreat article PinmemberJim Crafton9-May-02 16:21 
GeneralRe: Great article PinmemberSteve Chen9-May-02 19:10 
GeneralRe: Great article Pinmemberpoplarc3-Nov-02 20:07 
GeneralBitfield portability PinmemberPravin Wagh9-May-02 10:16 
I enjoyed Pete's article, and I wanted to share the following information with the readers regarding the use of Bitfields -- specifically their portability.
 
When using a bitfield, e.g. Flags.Disabled = 1, one should not make assumptions about how the compiler will store that bitfield in memory.
 
Though the programmer may have declared the field elements in a particular order, it's not safe to assume that the compiler has preserved that order when it generates the byte, word, long word, etc. that holds the field.
 
Thus, one should avoid doing this:
 
#define FLG_DISABLED 0x0004
if ( ((unsigned long) Flags) & FLG_DISABLED ) ...
 
This is not portable because the compiler may not have used 0x0004 for the bit.
 
A solution is to use macros that accomodate for the bitfield adjustment, or to use the explicit references for the flags, i.e. Flags.Disabled or IS_DISABLED(Flags) where the IS_DISABLED macro is appropriate for the platform.
 
VC++ seems to honor the programmer's intended bitfield declaration, but I have found that a gnu-based compiler we use on a PowerPC platform (Nintendo Game Cube) likes to reverse the bitfield order.
 
I do not know if all PowerPC compilers follow this convention, or if it's something related to the particular architecture. This bitfield reversal does not occur on other CPUs and platforms on which our code also runs.
 
It's a good caution for all programmers to be aware of, should the occasion arise to port code to another compiler, OS or CPU.
 
+pravin
GeneralRe: Bitfield portability Pinmemberilinov10-May-02 3:53 
Generalswap X, Y without 3rd var PinmemberY. Huang9-May-02 7:56 
GeneralRe: swap X, Y without 3rd var Pinmemberjfugate9-May-02 8:35 
GeneralRe: swap X, Y without 3rd var PinmemberY. Huang9-May-02 10:31 
GeneralRe: swap X, Y without 3rd var PinmemberAtlantys10-May-02 2:59 
GeneralRe: swap X, Y without 3rd var PinmemberJoao Vaz10-May-02 3:13 
GeneralRe: swap X, Y without 3rd var PinmemberChengFei He8-Nov-02 1:52 
GeneralRe: swap X, Y without 3rd var PinsussAleksandar Stojkov26-May-03 2:30 
GeneralRe: swap X, Y without 3rd var Pinmemberilinov10-May-02 3:40 
GeneralRe: swap X, Y without 3rd var PinmemberJamie Hale10-May-02 7:53 
GeneralRe: swap X, Y without 3rd var PinmemberDaniel Turini13-May-02 1:10 
GeneralRe: swap X, Y without 3rd var PinmemberCraig Henderson14-May-02 22:24 
GeneralRe: swap X, Y without 3rd var PinmemberY. Huang15-May-02 4:30 
GeneralRe: swap X, Y without 3rd var Pinmembermelwyn22-Aug-02 21:39 
GeneralRe: swap X, Y without 3rd var PinsussKochise13-Sep-02 2:06 
GeneralRe: swap X, Y without 3rd var PinmemberMoMad28-Sep-02 11:36 
GeneralRe: swap X, Y without 3rd var PinmemberAndreas Saurwein22-May-02 23:36 
GeneralRe: swap X, Y without 3rd var Pinmemberrbid7-Jan-05 21:48 
GeneralRe: swap X, Y without 3rd var Pinsusshedehodo8-Jun-03 2:36 
GeneralRe: swap X, Y without 3rd var Pinmemberzakkas248328-Sep-07 19:28 
GeneralA Suggestion PinmemberGil Rivlis9-May-02 7:14 
GeneralRe: A Suggestion PinmemberTim Smith9-May-02 7:45 
GeneralRe: A Suggestion PinmemberJoao Vaz10-May-02 3:07 
GeneralGood article but... Pinmemberilinov8-May-02 21:08 
GeneralRe: Good article but... PinmemberAnonymous8-May-02 21:21 
GeneralRe: Good article but... PinmemberPJ Arends8-May-02 21:23 
GeneralRe: Good article but... PinmemberTodd Smith9-May-02 6:57 
GeneralRe: Good article but... PinmemberChris Losinger9-May-02 7:02 
GeneralRe: Good article but... PinmemberTony Fontenot9-May-02 13:52 
GeneralRe: Good article but... PinmemberMike Stevenson17-May-02 6:45 
GeneralRe: Good article but... PinmemberLiam OHagan9-May-02 17:12 
GeneralRe: Good article but... PinmemberNick Parker9-May-02 18:32 
GeneralRe: Good article but... Pinmemberilinov10-May-02 3:54 
GeneralRe: Good article but... PinmemberAlexandru Savescu11-May-02 4:36 
GeneralRe: Good article but... Pinmembernoble22-May-02 18:19 
GeneralNice :-) PinmemberNish [BusterBoy]8-May-02 19:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 9 May 2002
Article Copyright 2002 by PJ Arends
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid