 # Manipulating Values in Your Programs

• Print
This chapter is from the book

## Bonus Material: For Those Brave Enough

For those brave enough, the following sections explain using the bitwise operators. This includes using the shift operators and the logical bitwise operators. Bitwise operators are a more advanced topic, so most beginning-level books skip over them. One reason they are advanced is that before understanding how these operators work, you need to understand how variables are truly stored.

TIP

It is valuable to understand the bitwise operators and how memory works; however, it is not critical to your understanding C#. If you feel brave, continue forward. If not, feel free to jump to the Summary and Workshop at the end of today's lessons. You can always come back and read this later.

### Storing Variables in Memory

To understand the bitwise operators, you must first understand bits. In yesterday's lesson on data types, you learned that the different data types take different numbers of bits to store. For example, a char data type takes 2 bytes. An integer takes 4 bytes. You also learned that maximum and minimum values can be stored in these different data types.

Recall that a byte is 8 bits of memory; 2 bytes is 16 bits of memory—2 x 8. Therefore, 4 bytes is 32 bits of memory. The key to all of this is to understand what a bit is.

A bit is simply a single storage unit of memory that can be either turned on or turned off just like a light bulb. If you are storing information on a magnetic medium, a bit can be stored as either a positive charge or a negative charge. If you are working with something such as a CD-ROM, the bit can be stored as a bump or as an indent. In all these cases, one value is equated to 0 and the other is equated to 1.

If a bit can store only a 0 or a 1, you are obviously very limited in what can be stored. To be able to store larger values, you use bits in groups. For example, if you use 2 bits, you can actually store four numbers, 00, 01, 10, and 11. If you use 3 bits, you can store eight numbers, 000, 001, 010, 011, 100, 101, 110, and 111. If you use 4 bits, you can store 16 numbers. In fact x bits can store 2x numbers, so a byte (8 bits), can store 28, or 256 numbers. Two bytes can store 216, or 65536 values.

Translating from these 1s and 0s is simply a matter of using the binary number system. Appendix C, "Understanding Number Systems," explains how you can work with the binary number system in detail. For now, understand that the binary system is simply a number system.

You use the decimal number system to count. Whereas the decimal system uses 10 numbers (0 to 9), the binary system uses 2 numbers. When counting in the decimal system, you use 1s, 10s, 100s, 1,000s, and so forth. For example, the number 13 is one 10 and three 1s. The number 25 is two 10s and five 1s.

The binary system works the same way, except that there are only two numbers, 0 and 1. Instead of 10s and 100s, you have 1s, 2s, 4s, 8s, and so on. In fact, each group is based on taking 2 to the power of a number. The first group is 2 to the power of 0, the second is 2 to the power of 1, the third is 2 to the power of 3, and so on. Figure 3.2 illustrates this. Figure 3.2 Binary versus decimal.

Presenting numbers in the binary system works the same way it does in the decimal system. The first position on the right is 1s, the second position from the right is 2s, the third is 4s, and so on. Consider the following number:

`1101`

To convert this binary number to decimal, you can multiply each value in the number times by positional value. For example, the value in the right column (1s) is 1. The 2s column contains a 0, the 4s column contains a 1, and the 8s column contains a 1. The result is this:

`1 + (0 _ 2) + (1 _ 4) + (1 _ 8)`

The final decimal result is this:

`1 + 0 + 4 + 8 `

This is 13. So, 1101 in binary is equivalent to 13 in decimal. This same process can be applied to convert any binary number to decimal. As numbers get larger, you need more bit positions. To keep things simpler, memory is actually separated into 8-bit units—bytes.

### Understanding the Shift Operators

C# has two shift operators that can be used to manipulate bits. These operators do exactly what their names imply—they shift the bits. The shift operators can shift the bits to the right using the >> operator or to the left using the << operator. These operators shift the bits within a variable by a specified number of positions. The format is as follows:

`New_value = Value [shift-operator] number-of-positions;`

Value is a literal or a variable, shift-operator is either the right (>>) or the left (<<) shift operator, and number-of-positions is how many positions you want to shift the bits. For example, if you have the number 13 stored in a byte, you know that its binary representation is as follows:

`00001101`

If you use the shift operator on this, you change the value. Consider the following:

`00001101 >> 2`

This shifts the bits in this number to the right two positions. The result is this:

`00000011`

This binary value is equivalent to the value of 3. In summary, 13 >> 2 equals 3. Consider another example:

`00001101 << 8`

This example shifts the bit values to the left eight positions. Because this is a single-byte value, the resulting number is 0.

### Manipulating Bits with Logical Operators

In addition to being able to shift bits, you can combine the bits of two numbers. Three bitwise logical operators can be used, as shown in Table 3.5.

#### Table 3.5 Logical Bitwise Operators

 Operator Description | Logical OR bitwise operator & Logical AND bitwise operator ^ Logical XOR bitwise operator

Each of these operators is used to combine the bits of two binary values. Each has a different result.

#### The Logical OR Bitwise Operator

When combining two values with the logical OR bitwise operator (|), you get the following results:

• If both bits are 0, the result is 0.

• If either or both bits are 1, the result is 1.

Combining 2 byte values results in the following:

Value 1: 00001111
Value 2: 11001100
--------
Result: 11001111

#### The Logical AND Bitwise Operator

When combining two values with the logical AND bitwise operator (&), you get the following result:

• If both bits are 1, the result is 1.

• If either bit is 0, the result is 0.

Combining 2 byte values results in the following:

Value 1: 00001111
Value 2: 11001100
--------
Result: 00001100

#### The Logical XOR Operator

When combining two values with the logical XOR bitwise operator (^), you get the following result:

• If both bits are the same, the result is 0.

• If 1 bit is 0 and the other is 1, the result is 1.

Combining 2 byte values results in the following:

Value 1: 00001111
Value 2: 11001100
--------
Result: 11000011

Listing 3.7 illustrates some of the bitwise operators.

#### Listing 3.7 bitwise.cs—The Bitwise Operators

``` 1: // bitwise.cs - Using the bitwise operators
2: //----------------------------------------------------
3:
4: class bitwise
5: {
6:   public static void Main()
7:   {
8:    int ValOne = 1;
9:    int ValZero = 0;
10:    int NewVal;
11:
12:    // Bitwise XOR Operator
13:
14:    NewVal = ValZero ^ ValZero;
15:    System.Console.WriteLine("\nThe XOR Operator: \n 0 ^ 0 = {0}",
16:                     NewVal);
17:    NewVal = ValZero ^ ValOne;
18:    System.Console.WriteLine(" 0 ^ 1 = {0}", NewVal);
19:
20:    NewVal = ValOne ^ ValZero;
21:    System.Console.WriteLine(" 1 ^ 0 = {0}", NewVal);
22:
23:    NewVal = ValOne ^ ValOne;
24:    System.Console.WriteLine(" 1 ^ 1 = {0}", NewVal);
25:
26:    // Bitwise AND Operator
27:
28:    NewVal = ValZero & ValZero;
29:    System.Console.WriteLine("\nThe AND Operator: \n 0 & 0 = {0}",        _NewVal);
30:
31:    NewVal = ValZero & ValOne;
32:    System.Console.WriteLine(" 0 & 1 = {0}", NewVal);
33:
34:    NewVal = ValOne & ValZero;
35:    System.Console.WriteLine(" 1 & 0 = {0}", NewVal);
36:
37:    NewVal = ValOne & ValOne;
38:    System.Console.WriteLine(" 1 & 1 = {0}", NewVal);
39:
40:    // Bitwise OR Operator
41:
42:    NewVal = ValZero | ValZero;
43:    System.Console.WriteLine("\nThe OR Operator: \n 0 | 0 = {0}",
44:                   NewVal);
45:    NewVal = ValZero | ValOne;
46:    System.Console.WriteLine(" 0 | 1 = {0}", NewVal);
47:
48:    NewVal = ValOne | ValZero;
49:    System.Console.WriteLine(" 1 | 0 = {0}", NewVal);
50:
51:    NewVal = ValOne | ValOne;
52:    System.Console.WriteLine(" 1 | 1 = {0}", NewVal);
53:   }
54: }
The XOR Operator:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

The AND Operator:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

The OR Operator:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1```

Listing 3.7 summarizes the logical bitwise operators. Lines 8–9 define two variables and assign the values 1 and 0 to them. These two variables are then used repeatedly with the bitwise operators. A bitwise operation is done, and the result is written to the console. You should review the output and see that the results are exactly as described in the earlier sections.

### Flipping Bits with the Logical NOT Operator

One other bitwise operator is often used. The logical NOT operator (~) is used to flip the bits of a value. Unlike the logical bitwise operator mentioned in the previous sections, the NOT operator is unary—it works with only one value. The results are as follows:

• If the bit's value is 1, the result is 0.

• If the bit's value is 0, the result is 1.

Using this on an unsigned byte that contains the value of 1 (00000001) would result in the number 254 (11111110).