1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Low Level Operations

By David Bolton, About.com

1 of 10

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.

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. C Programming Tutorial - Low Level Operations>

©2009 About.com, a part of The New York Times Company.

All rights reserved.