# Manipulating Values in Your Programs

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).

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.