K&R 2-7 - Invert a bitfield from a number

This is my solution to the Exercise 2-7 of K&R C book. The assignment is:

Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Note: It's assumed that the rigthmost bit of a number has position 0.

Example: If x = 8 (00001000 in binary), p = 2 and n = 3, the result should be 20 (00010100), because bits 2, 3 and 4 are inverted.

Code:

#include <stdio.h>  unsigned invert(int x, int p, int n);  int main(void) {     // just a test     printf("%u\n", invert(8, 2, 3));     return 0; }  unsigned invert(int x, int p, int n) {     /* The right part makes a mask with 1's under the        desired bits to be inverted. Then, they're inverted        by X0Ring it and x.     */     return x ^ (~(~0 << n) << p); }

I would love to know how to improve it, be it in style, efficiency, etc.

Replay

Category: c# Time: 2016-07-29 Views: 0
Tags: bitwise