   Next: The C Preprocessor Up: Low Level Operators Previous: Bit Fields

# Exercises

1. Write a function that prints out an 8-bit (unsigned char) number in binary format.

">

2. Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of an unsigned char variable y (leaving other bits unchanged).

E.g. if (170 decimal) and (167 decimal) and and say then you need to strip off 3 bits of y (111) and put them in x at position to get answer .

Your answer should print out the result in binary form (see Exercise although input can be in decimal form.

Your output should be like this:

```
x = 10101010 (binary)
y = 10100111 (binary)
setbits n = 3, p = 6 gives x = 10111010 (binary)```

">
(unit7:functions:bits)

3. Write a function that inverts the bits of an unsigned char x and stores answer in y.

Your answer should print out the result in binary form (see Exercise although input can be in decimal form.

Your output should be like this:

```
x = 10101010 (binary)
x inverted = 01010101 (binary)```

">
(unit7:functions:inv)

4. Write a function that rotates (NOT shifts) to the right by n bit positions the bits of an unsigned char x.ie no bits are lost in this process.

Your answer should print out the result in binary form (see Exercise although input can be in decimal form.

Your output should be like this:

```
x = 10100111 (binary)
x rotated by 3 = 11110100 (binary)```

">
(unit7:functions:rot)

Note: All the functions developed should be as concise as possible

Dave.Marshall@cm.cf.ac.uk
Fri May 20 13:40:49 BST 1994