You are here:About>Computing & Technology>C / C++ / C#> C> C Tutorials> C Programming Tutorial - Low Level Operations
About.comC / C++ / C#
Newsletters & RSSEmail to a friendSubmit to Digg
Elsewhere on the Web

C Programming Tutorial - Low Level Operations

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

Dealing with Bits and Bytes

In its role as a high level assembler used for writing operating systems, C is often used to access memory locations and change individual bits. You might for example need to access individual bits in an int. It can sometimes be useful to conserve memory by using a byte to hold 8 flags though with an abundance of ram it's common to just use one byte per flag or even one per int. Knowing how to extract or alter individual bits is still worthwhile knowing; you may never have to use it but when you have to maintain code that does you'll know how to.

If you need to remind yourself about binary this article What is Software may help.

An int holds 32 bits. It's conventional to number them with the highest bit on the left (31) to right (0) for 32 bit CPUs and 63 to 0 for 64 bit CPUs.

33222222-22221111-11111100-00000000
10987654-32109876-54321098-76543210
The dash shows where the break between bytes is located. To access individual bits we need to work on whole bytes or ints and then isolate the particular bit. This is where the binary operations, "and", "or" and "xor" are used. Don't confuse these with the same name logical operations. Logical operations use two characters, binary use one. A "Logical and" is like this
if (a && b )
  {
    c
  }
and means that if expression a is non zero and expression b is non zero then do statement c;

A "Binary and" is like this, with one & character.

c= a & b;
c = the result of "binary anding" the two numbers a, b together. If a,b and c are all bytes then this "binary ands" all 8 bits of a with the corresponding bits of b to get c. Each bit of c is 1 if the corresponding bits of a and b are both 1. If either a or b is zero (or both) then the bit in c is also 0.
a 100101102
b 011111002
--------------------
a & b 000101002

On the next Page - Or and Xor.

  1. Dealing with Bits and Bytes
  2. Manipulating Individual Bits with Binary Operations
  3. Example 1 - Using a Binary And to Extract Bits
  4. More about Example 1
  5. Another Example that Demonstrates all three Binary Operations
  6. A look at Xor in Lightweight Encryption
  7. An example using Simple Xor Encryption
  8. Unions- Holding Data in the Same Place
  9. Where would you use a Union?
  10. Packing Bits with Bit Fields

Previous | Next >>

Elsewhere on the Web

 All Topics | Email Article | | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.