patterncMinor
K&R 2-7 - Invert a bitfield from a number
Viewed 0 times
invertbitfieldfromnumber
Problem
This is my solution to the Exercise 2-7 of K&R C book. The assignment is:
Write a function
Note: It's assumed that the rigthmost bit of a number has position 0.
Example: If
Code:
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
unsigned invert(unsigned x, int p, int n);
int main(void)
{
// just a test
printf("%u\n", invert(8, 2, 3));
return 0;
}
unsigned invert(unsigned 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);
}Solution
Just a few notes, since the code is so short:
-
Put your
-
You don't have to return
C99 & C11 §5.1.2.2(3)
...reaching the
value of
-
Move your comment to the top of the function and explicitly say what the parameters are and what the output will be.
-
Your function parameter names could be better:
-
Those parameters to your function could be declared
-
Does your function perform as is supposed to with negative numbers? Zeros? Other edge cases? You should have more tests in your code to make sure you get the expected behavior, and if not handle those edge cases more appropriately. Use
-
Put your
main after all of your other function declarations so you don't have to declare the function prototypes at the top.-
You don't have to return
0 at the end of main(). The C standard knows how frequently this is used, and lets us omit it.C99 & C11 §5.1.2.2(3)
...reaching the
} that terminates the main() function returns avalue of
0. -
Move your comment to the top of the function and explicitly say what the parameters are and what the output will be.
-
Your function parameter names could be better:
unsigned invert(unsigned num, int position, int num_bits)-
Those parameters to your function could be declared
const-
Does your function perform as is supposed to with negative numbers? Zeros? Other edge cases? You should have more tests in your code to make sure you get the expected behavior, and if not handle those edge cases more appropriately. Use
assert from the standard library header `` to help with this.Code Snippets
unsigned invert(unsigned num, int position, int num_bits)Context
StackExchange Code Review Q#136337, answer score: 8
Revisions (0)
No revisions yet.