   Home Books by K. N. King Short courses Recommended books Recommended links FAQ ### Chapter 20

2. [was #2] To toggle a bit in a variable `i`, apply the exclusive-or operator (`^`) to `i` and a mask with a 1 bit in the desired position, then store the result back into `i`. To toggle bit 4, for example, use the statement

```i = i ^ 0x0010;
```

or, more concisely,

```i ^= 0x0010;
```

4. [was #4] ``` ```

``` ```
````#define MK_COLOR(r,g,b) ((long) (b) << 16 | (g) << 8 | (r))`
```

6. [was #6; modified]

(a)

```#include <stdio.h>

unsigned short swap_bytes(unsigned short i);

int main(void)
{
unsigned short i;

printf("Enter a hexadecimal number (up to four digits): ");
scanf("%hx", &i);
printf("Number with bytes swapped: %hx\n", swap_bytes(i));
return 0;
}

unsigned short swap_bytes(unsigned short i)
{
unsigned short high_byte = i << 8;
unsigned short low_byte = i >> 8;

return high_byte | low_byte;
}
```

(b)

```unsigned short swap_bytes(unsigned short i)
{
return i << 8 | i >> 8;
}
```

8. [was #8]

(a) The value of `~0` is a number containing all 1 bits. Shifting this number to the left by `n` places yields a result of the form 1…10…0, where there are `n` 0 bits. Applying the `~` operator to that number yields a result of the form 0…01…1, where there are `n` 1 bits.

(b) It returns a bit-field within `i` of length `n` starting at position `m`. Positions are assumed to be numbered starting from the rightmost bit, which is position 0.

14. [was #9]

```struct IEEE_float {
unsigned int fraction: 23;   /* members may need to be reversed */
unsigned int exponent: 8;
unsigned int sign: 1;
};
``` 