Thursday, January 10, 2013

Low level operations in c

Bitwise Operators in C

Introduction

When you learn to program in a high-level language like C (although C is fairly low-level, as high-level languages go), the idea is to avoid worrying too much about the hardware. You want the ability to represent mathematical abstractions, such as sets, etc. and have high level language features like threads, higher-order functions, exceptions.
High-level languages, for the most part, try to make you as unaware of the hardware as possible. Clearly, this isn't entirely true, because efficiency is still a major consideration for some programming languages.
C, in particular, was created to make it easier to write operating systems. Rather than write UNIX in assembly, which is slow process (because assembly code is tedious to write), and not very portable (because assembly is specific to an ISA), the goal was to have a language that provided good control-flow, some abstractions (structures, function calls), and could be efficiently compiled and run quickly.
Writing operating systems requires the manipulation of data at addresses, and this requires manipulating individual bits or groups of bits.
That's where two sets of operators are useful: bitwise operators and bitshift operators.
You can find these operators in C, C++, and Java (and presumably C#, since it's basically Java). Bitwise operators allow you to read and manipulate bits in variables of certain types.
Even though such features are available in C, they aren't often taught in an introductory level programming course. That's because intro level courses prefer to emphasize abstraction. With many departments using Java, there's a trend to increase what's abstract, and not get into the representation.
For example, some languages have support for stacks, queues, hashtables, and so forth. These "canned" data structures are meant to provide you, the programmer, with objects that perform certain tasks, while relieving you of the tedium and detail of understanding how the data is represented.
Nevertheless, if you intend to do some work in systems programming, or other forms of low-level coding (operating systems, device drivers, socket programming, network programming), knowing how to access and manipulate bits is important.

Generic Bitwise Operations

Bitwise operators only work on a limited number of types: int and char. This seems restrictive--and it is restrictive, but it turns out we can gain some flexibility by doing some C "tricks".
It turns out there's more than one kind of int. In particular, there's unsigned int, there's short int, there's long int, and then unsigned versions of those ints.
The "C" language does not specify the difference between a short int, an int and a long int, except to state that:
   sizeof( short int ) <= sizeof( int ) <= sizeof( long )
You will find that these sizes vary from ISA to ISA, and possibly even compiler to compiler. The sizes do not have to be distinct. That means all three sizes could be the same, or two of three could be the same, provided that the above restrictions are held.
Bitwise operators fall into two categories: binary bitwise operators and unary bitwise operators. Binary operators take two arguments, while unary operators only take one.
We're going to discuss binary operators first, and we'll do in the context of a fake binary operator called @. Thus, we write x @ y to perform bitwise @ on x and y.
Bitwise operators, like arithmetic operators, do not change the value of the arguments. Instead, a temporary value is created. This can then be assigned to a variable. For example, when you write x + y, neither x nor y have their value changed.
Let's assume that we are doing bitwise @ on two unsigned int variables. Let's assume that unsigned ints use 32 bits of memory. We define two variables X and Y where
   X = x31x30....x0
   Y = y31y30....y0
We want to be able to refer to each bit of X and Y, which we do so by writing out the bits by writing the variable name in lowercase and adding the appropriate subscript for thie bit number.
The subscripts follow the convention we've used so far. The least significant bit has a subscript of 0, and is the rightmost bit. The most significant bit has a subscript of N-1 (for N bits), and is the leftmost bit. In this case N = 32 so the MSb has a subscript of 31.
Let's define @1 to be the @ operation performed on two individual bits. @ is performed on all 32 bits simultaneously.
Furthermore, let's call the temporary value created, T. Normally, this temporary value does not have a name. It is generated while the program is running, and used in other computations. Thus, when you write c = a + b, a temporary value is created for the sum a + b, and this temporary value then gets copied into c.
Of course, for efficiency, the temporary value might not be generated, and the value written directly to c. For more complex statements, such as c = (a + b) - d, temporary values are often created to store intermediate results. These temporary values are created by the runtime system, and are not given variable names.
We define Z = X @ Y as:
   zi = xi @1 yi, for 0 <= i <= N - 1 
In words, to compute the ith bit of Z, you should perform the operation on the ith bit of X and ith bit of Y.

Bitwise AND

This makes more sense if we apply this to a specific operator. In C/C++/Java, the & operator is bitwise AND. The following is a chart that defines &1, defining AND on individual bits.
  xi     yi   xi &1 yi
0 0 0
0 1 0
1 0 0
1 1 1
We can do an example of bitwise &. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x & y 1 0 0 0

Bitwise OR

The | operator is bitwise OR (it's a single vertical bar). The following is a chart that defines |1, defining OR on individual bits.
  xi     yi   xi |1 yi
0 0 0
0 1 1
1 0 1
1 1 1
We can do an example of bitwise |. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x | y 1 1 1 0

Bitwise XOR

The ^ operator is bitwise XOR. The usual bitwise OR operator is inclusive OR. XOR is true only if exactly one of the two bits is true. The XOR operation is quite interesting, but we defer talking about the interesting things you can do with XOR until the next set of notes.
The following is a chart that defines ^1, defining XOR on individual bits.
  xi     yi   xi ^1 yi
0 0 0
0 1 1
1 0 1
1 1 0
We can do an example of bitwise ^. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x ^ y 0 1 1 0

Bitwise NOT

There's only one unary bitwise operator, and that's bitwise NOT. Bitwise NOT flips all of the bits.
There's not that much to say about it, other than it's not the same operation as unary minus.
The following is a chart that defines ~1, defining NOT on an individual bit.
  xi   ~1 xi
0 1
1 0
We can do an example of bitwise ~. It's easiest to do this on 4 bit numbers (although only 2 bits are necessary to show the concept).
Variable b3 b2 b1 b0
x 1 1 0 0
z = ~x 0 0 1 1

Uses of Bitwise Operations

Occasionally, you may want to implement a large number of Boolean variables, without using a lot of space.
A 32-bit int can be used to stored 32 Boolean variables. Normally, the minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples of bytes. However, only one bit is necessary to represent a Boolean value.
You can also use bits to represent elements of a (small) set. If a bit is 1, then element i is in the set, otherwise it's not.
You can use bitwise AND to implement set intersection, bitwise OR to implement set union.
In upcoming notes, you'll learn how to find the value of individual bits of a char or int.

Facts About Bitwise Operators

Consider the expression x + y. Do either x or y get modified? The answer is no.
Most built-in binary operators do not modify the values of the arguments. This applies to logical operators too. They don't modify their arguments.
There are operators that do assignment such as +=, -=, *=, and so on. They apply to logical operators too. For example, |=, &=, ^=. Nearly all binary operators have a version with = after it. 

Bitshift Operators

Did you think that << or >> was invented in C++? That these operators did not exist in C? If so, you're wrong. These operators did exist in C. Of course, they were not the stream insertion and extraction operators. These were bitshift operators.
The bitshift operators take two arguments, and looks like:
  x << n
  x >> n
where x can be any kind of int variable or char variable, and n can be any kind of int variable.
Think of x as a bitstring (since it is), and n as the number of bits to shift left or write. You should be familiar with shifting, because it's a fundamental operation in, say, insertion sort.

Restrictions

Like bitwise operators, you can only perform bitshift operations on x (the left argument) on certain types: in particular, any kind of int and any kind of char.
There are sneaky ways to shift bits even if you use other types (say, float). This involves tricks with casting. We'll see this at the end of these notes.

Operator <<

The operation x << n shifts the value of x left by n bits.
Let's look at an example. Suppose x is a char and contains the following 8 bits.
b7 b6 b5 b4 b3 b2 b1 b0
1 1 0 0 0 1 1 1
If we shift left by 3 bits, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 1 1 1 0 0
When you shift left by k bits then, bi + k = bi. If i + k > N, then bit bi fell off the left edge. If i < K, then bi = 0. In other words the low K bits are all 0's.
That means that as you shift left, the bits on the high end (to the left) fall off, and 0 is shifted in from the right end.

Left shifting is multiplying by 2K

If you shift left on an unsigned int by K bits, this is equivalent to multiplying by 2K. Why is that? Fix your attention to a bit that has a value of 1. Suppose bi = 1 prior to shifting. This bit contributes 2i to the overall value.
If you shift left by K bits, then this 1 will now appear as bi + K. Thus, that bit contributes 2i + K, which is, of course, equal to 2i * 2K (using law of exponents), i.e., it's multiplying by 2K.
Of course, this multiplication can only go so far. For unsigned int, when the first "1" falls off the left edge, the operation has overflowed. That is, you've multiplied by 2K such that the result is larger than the largest possible unsigned int.
Shifting left on signed values also works, but overflow occurs when the most significant bit changes values (from 0 to 1, or 1 to 0).
It's not nearly as obvious that shifting left in 2C would actually multiply by 2. The easiest way to view this is to think about 1C. The difference between 1C and 2C is 1. That means, if you're looking at a negative number, and focus on the bits with 0, they shift when they move to the left. Now, the correponding positive value is computed by flipping the bits (thus, those 0 bits are now 1), and effectively, you're watching 1 bits move left.
Another way to view this is to recall that 2C is equivalent to flipping the bits left of the rightmost 1. Again, if you look at the 0's left of that rightmost 1, they will eventually become 1's and they are shifting to the left.

Operator >>

Left shifting generally creates few problems regardless of type. 0's are shifted from the least significant end, and bits fall off the most significant end. Right shifting causes a few more problems. When shifting to the right for unsigned int, bits fall off the least significant end, and 0's are shifted in from the most significant end. This is also known as logical right shift (logical shifts shift in 0's).
However, with signed int, the story is different. What right shifting does depends on the compiler. One possibility is to shift in 0's, just as unsigned int's do. If this occurs, then you divide by 2K (if you're shifting K bits), but only for non-negative values of x. For negative values, you've made it positive, and it no longer makes sense that this operation is equivalent to dividing by 2K.
Compilers may also shift in the sign bit. Thus, if x is negative, the sign bit is 1, so 1's are shifted from the most significant end. If x is non-negative, 0's are shifted from the most significant end. This is called an arithmetic right shift since the sign bit is shifted in. Thus, if you shift right by K bits, then K 1's or K 0's are shifted in.
Let's look at an example of this. Suppose x looks like before:
b7 b6 b5 b4 b3 b2 b1 b0
1 1 0 0 0 1 1 1
Let's shift right by 3 bits. If the sign bit is shifted in, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
1 1 1 1 1 0 0 0
If 0's are shifted in, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 1 1 0 0 0

Shifting Doesn't Change Values

Here's one of those rather annoying facts about C, that is perfectly consistent with the way C does things. Suppose x = 3 and n = 2. What does the following code do?
  int x = 3 ;
  int n = 2 ;
  x << n ;
  cout << x << endl ; 
What does it print? The answer is 3. The answer is NOT 12.
Why is that? Suppose you were asked to sum x + y. What will happen to x or y? Of course, you know that nothing happens to them. But then where does the sum go? A temporary value is created internally, and that value is typically used to assign to some result or printed.
The same thing happens when you do x << n. It creates a temporary value with a bitshifted version of x, but does not change the value of x.
So, how do you save the change? Simple, just assign it.
  x = x << n ;
  cout << x << endl ; 
This prints out 12 (if x is 3 and n is 2). There's an equivalent way to do this. Use the <<=; operator. Nearly every C binary operator has a version with ='s after it.
  x <<= n ;
  cout << x << endl ; 

Shifting Bits for other types

Suppose you wish to shift left on float variables. The compiler will complain that you can't do this. Bitwise/bitshift operations aren't defined on float variables. So, what can you do?
Trick the compiler.
How do you do that?
Make it think the float is an int.
Here's the wrong way to do it. You can try to cast the float to an int. But if you do this, you have two problems. First, casting creates a temporary value. Even if you save this, the bits will actually change. A float that's cast to an int causes the fractional part to be truncated, and what's more, it changes the representation from IEEE 754 to 2C.
Nevertheless, casting is the right idea. Here's how to do it.
   float x ;
   int * ptr = (int *) (& x) ;
   *ptr <<= n ; // left shift by n bits
You make a pointer that points to the float with same number of bytes, then you shift based on the dereferenced pointer. At this point, when we manipulate *ptr, we're actually manipulating x.

Some facts:
  • Shifting left using << causes 0's to be shifted from the least significant end (the right side), and causes bits to fall off from the most significant end (the left side). This occurs whether the variable is signed or unsigned.
  • Shifting left by K bits is equivalent to multiplying by 2K.
  • Shifting right using >> causes 0's to be shifted from the most significant end (the left side), and causes bits to fall off from the least significant end (the right side) if the number is unsigned. If it's signed, then it's implementation depedendent. It may shift in the sign bit from the left, or it may shift in 0's (it makes more sense to shift in the sign bit).
  • For unsigned int, and sometimes for signed int, shifting right by K bits is equivalent to dividing by 2K (using integer division).
  • Bitshifting doesn't change the value of the variable being shifted. Instead, a temporary value is created with the bitshifted result.

Mask

For our examples, we'll work with 8-bit bitstrings. I could look at 32 bit ints, but they're 32 bits, and that's a lot of bits to write. The principle still apply.
We're going to consider bitstring pattern called a mask. Here's one example of a mask.
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 0 1 0 0 0
This is a bitstring with exactly one bit that has a value of 1. In this example, b3 = 0.
Similarly, the bitflipped version of this is also considered a mask.
b7 b6 b5 b4 b3 b2 b1 b0
1 1 1 1 0 1 1 1
What's the purpose of a mask? The purpose is to either access an individual bit (or range of bits) or to modify an individual bit (or range of bits). 

Using the Mask

Let's see how we can use this mask to determine whether a bit is set or clear. Before we can do that, perhaps we should define what it means to be set or clear.
  • To set a bit means to make the value of the bit 1.
  • To clear a bit means to make the value of the bit 0.
Suppose you're asked to write a function that returns true if bit i is set, and false if it's clear. We'll call this function isBitISet(). Here's the prototype:
bool isBitISet( unsigned char ch, int i ) ;
Here's the code.
bool isBitISet( unsigned char ch, int i ) 
{
   unsigned char mask = static_cast( 1 << i ) ;
   return mask & ch ;   
}
It looks pretty simple, doesn't it? Create a mask, then use bitwise AND on the character. Here's why it works.
ch b7 b6 b5 b4 b3 b2 b1 b0
mask 0 0 0 0 1 0 0 0
result = ch & mask 0 0 0 0 b3 0 0 0
We don't particularly care what the character looks like. Just assume it's some 8-bit bitstring, b7...b0. To distinguish the character from the mask, let's label the bits of the mask as m7...m0.
The mask has bit m3 set, though 3 was picked arbitrarily. Notice what happens when you bitwise AND the mask and the character.
The bits which are 0 in the mask cause the result to also be 0 (since 0 & bi = 0). Bit b3 is ANDed with the '1' appearing in the mask at position m3. That results in b3.
If b3 = 1, then result is non-zero. If b3 = 0, then result is zero.
The only interesting part is the return type. The result of the AND operation is an unsigned char. We're returning a bool (in C, you'd return an int or a short).
In C++, converting between char, int, and bool rarely requires a cast. Basically, anything that evaluates to 0 for a given type, is false when converted to a bool Anything that evaluates to a non-zero value (which doesn't have to be 1), evaluates to true.

Is Any Bit Set Within a Range?

In the last set of notes, we wrote a C function that would determine whether bit i was set or not. Can we generalize this function? In particular, can we implement the following prototype?
bool isBitSetInRange( char ch, int low, int high ) ;
This function returns true if any bit within bhigh...blow had a value of 1. We assume that low <= high. Note that all bits could be 1, or some bits could be 1, or exactly 1 bit in the range could be 1, and they would all return true. You return false only when all the bits in that range are 0. In order to implement this function, we need to modify the mask. In particular, suppose low = 3 and high = 5, then we would expect the mask to look like:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 1 1 1 0 0 0

How to Create a Mask with a Range

So we want to write code that creates a mask that looks like the one in the previous section. How can we do this? There are at several ways to do this. Method 1 Write a for-loop that checks if bit i is set, from the previous section.
   for ( int i = low ; i <= high ; i++ )
     if ( isBitISet( ch, i )
       return true ;
   // If it didn't return true in the for-loop, then return false
   return false ;
The nice thing about this code is that it reuses the previous code. As a computer science major, the first solution ought to be one that uses an old solution. However, the main drawback is using a loop. If the bitstring had been much longer (say, 32 or 64 bits), using a loop is more inefficient than not using one.
Method 2 This is somewhat complicated, so we'll need to break it down into steps.
  • First, we need to create a mask with the appropriate number of 1's. Suppose we want k 1's. Initially, we'll create a mask with n - k 0's, followed by k 1's. This is easier (for now) than creating the actual mask we need. The question is how to compute k given low and high. This is a classic off-by-one situation. Your first instinct might be high - low. But this would be incorrect. If the index high == low, then high - low == 0.
    That's not what you want. When high == low, you want to test for a single bit, i.e. bhigh (which is the same as blow since high == low). Thus, you want the formula to equal 1, when high == low.
    So, the formula should be high - low + 1.
    Here's the code to do this.
       unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
       int numOnes = (high - low) + 1 ; 
       int numBits = sizeof( unsigned char ) * 8 ;
    
       // creates (numBits - numOnes) 0's followed by numOnes 1's
       mask >>= ( numBits - numOnes ) ; 
    
  • Then, we need to shift left to place the 1's in the correct spot. The question is how much to shift left. The answer is abit tricky. Here's how to figure the answer. Think about the least significant bit. It's at position b0. It currently has a value of 1. Where should this bit end up? Since it's the rightmost bit, it should be the rightmost 1 when we shift left. And where's the rightmost 1? It's at blow. So we need to shift left by low bits. The remaining 1's shift left with it, and the leftmost 1 should land at bhigh because we computed the number of 1's ahead of time.
       mask <<= low ;
    
So, the entire code to create the mask looks like:
   unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
   int numOnes = (high - low) + 1 ; 
   int numBits = sizeof( unsigned char ) * 8 ;

   // creates (numBits - numOnes) 0's followed by numOnes 1's
   mask >>= ( numBits - numOnes ) ; 
   mask <<= low ; // shift left group of 1's to correct location
Notice that no loops were used.
The one possible problem we have is the mask being shifted to the right. If we had used a signed char, instead of an unsigned char, we might have had the sign bit shifted in from the left. That would not create the desired mask (instead, it would leave us with all 1's).
So, here's a solution that avoids this problem.

   unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
   int numOnes = (high - low) + 1 ; 

   // creates (numBits - numOnes) 1's followed by numOnes 0's
   mask <<= numOnes ; 

   // creates (numBits - numOnes) 0's followed by numOnes 1's
   mask = ~mask ;
   mask <<= low ; // shift left the group of 1's to correct location
By left shifting, we guarantee that 0's are shifted in from the right, regardless of whether the type is signed or unsigned. However, we need the additional step of negating the mask to get the pattern we want. This solution avoids using right shifts, thus should be more portable.
Method 3 The previous solution is moderately complicated to think about, though once you get used to the idea, it isn't all that bad.
A third way to produce the mask is to not only use bitshift operators, but also to use subtraction.
Consider the following two masks.
  b7 b6 b5 b4 b3 b2 b1 b0
maskHigh 0 0 1 1 1 1 1 1
maskLow 0 0 0 0 0 1 1 1
maskHigh - maskLow 0 0 1 1 1 0 0 0
So, if we could create a mask with high 1's and a mask with low 1's (as shown above), then subtract, we'd get the desired mask.
How can we get a mask with k 1's? To answer this, answer the following question. Suppose you have 1000 in base 10. This is 1, followed by 3 zeroes. If you subtract 1 from 1000, what do you get? You get 999. Suppose you have 100000. This is 1 followed by 5 zeroes. If you subtract 1 from that, you get 99999.
If you have 1, followed by k zeroes and you subtract 1 from it, then what do you get? You get k 9's.
Now, if this were binary, and you have 1 followed by k zeroes, and you subtract 1, what would you get? You'd get k 1's.
So here's the question. How do get 1, followed by k 0's? You bitshift 1 to the left by k!
  unsigned int mask = 1 << k ;
  mask -= 1 ; // Produces k 1's
So, here's how you get maskHigh and maskLow.
  unsigned char maskHigh = ( 1 << ( high + 1 ) ) - 1 ;
  unsigned char maskLow = ( 1 << low ) - 1 ;
  unsigned char mask = maskHigh - maskLow ;
There is a slight awkwardness when computing maskHigh. We want the leftmost 1 to appear at bhigh. This means when we create the 1, followed by k zeroes, the "1" has to be shifted to bit position bhigh + 1. On the other hand, no such problems occur with maskLow. The string of 1's we want appear in the correct location by shifting 1 to blow.
If you're observant, you'll notice that when we compute mask, we're performing a computation that's of the form (x - 1) - (y - 1). Notice the 1's cancel, and you get (x - y).
So, we can get the mask without subtracting 1, as in:
  unsigned char mask = ( 1 << ( high + 1 ) ) - ( 1 << low ) ;
Which method is perferable? Method 2 is a little complicated, but is completely restricted to bitwise and bitshift operators. The advantage of that is that it works on signed and unsigned quantities.
Method 3 is simpler to understand, but uses subtraction. This turns out to work whether the type is signed or unsigned.

Putting it All Together

Once you create the mask, the code is really simple to check the range.
bool isBitSetInRange( char ch, int low, int high ) 
{
   unsigned char mask = .... ;
   // code to create mask

   return ch & mask ;
}
It's the same as before. This time, however, ch & mask may produce a result that has more than single bit with a value of 1, whereas the mask that checked for bit i being one could only produce a result that has, at most, one bit with a value of 1. However, it doesn't matter how many bits are 1. As long as at least one bit is 1, then the result is non-zero, and thus, the return value is true.

How to Set a Bit

So far, we've written functions to determine the value of individual bits of a number, or to determine if, within some range of bits, whether any bit was set. I'm sure you're interested in actually modifying bits. Once you understand masks, it's easy to modify individual bits.
Here's the prototype of the function we wish to implement.

unsigned char setBit( unsigned char ch, int i ) ;
This will take a character as input, set bi to 1, and return that new character, while leaving the original character untouched (which happens because the original character is passed by value, which means it's a copy of the argument).
Here's the code:

unsigned char setBit( unsigned char ch, int i ) 
{
  unsigned mask = 1 << i ;  // we could cast to unsigned char, just to be safe
  return mask | char ;  // using bitwise OR
}
Let's see how this works on an example:
  b7 b6 b5 b4 b3 b2 b1 b0
ch 1 0 0 0 0 0 1 1
mask 0 0 0 0 1 0 0 0
ch & mask 1 0 0 0 1 0 1 1
Instead of bitwise AND, we use bitwise OR. If you perform bitwise OR on a bit b with 0, you get back bit b. Thus, for all the bit positions in the mask with zero (in the example above, it's every bit except bit b3 in the mask), the corresponding bit position of ch & mask is just the value of the corresponding bit position in ch.
In other words, whereever there's a 0 in the mask, the original bit value in ch is preserved. For example, b7 = 1 in ch and the mask has a 0 in that position. The result ch & mask also has a 1 at that same bit position.
In fact, the only bit position that can potentially change in the result is the bit position that's a 1 in the mask. The mask has a 1 at b3. When you OR a bit b with 1, you get a 1 as a result.
Thus, this causes b3 to be 1 regardless of what b3 is in ch.
This is exactly the effect we're looking for. Setting b3 to 1 in the result, but leaving all other bits unchanged.


No comments:

Post a Comment