"Inserting" part of a bitset into another
This is Exercise 2-6 on the K&R book, 2nd edition. The reader is asked to:
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 y, leaving the other bits unchanged.
Parameters Description
Here's what each parameter does informally:
- x -> serves as the "destination" bitset
- y -> serves as the "source" bitset
- p -> serves as the insertion point for the bits from y to be inserted on x
- n -> serves as the length of the segment to "cut" from y and replace in x
Special Notes
- I've tested with a number of different scenarios, and this code has passed all of them.
- At the bottom of the question there's an outline of a test-case and my logic behind solving the problem
Code
#include <stdio.h>
//setbits: returns x with n bits that begin at p set to the rightmost n bits of y
//informally: "chop" n bits right->left from y, insert on x at position p
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
return ((~(~0 << n) & y) << p) | ((~(~(~0 << n) << p)) & x);
}
int main(void) {
// Example test cases:
// First scenario:
// x = 100 -> 0110 0100
// y = 5 -> 0000 0101
// p = 4
// n = 3
// Expected outcome: 0101 0100 (84)
// Second scenario:
// x = 94 -> 0101 1110
// y = 195 -> 1100 0011
// p = 0
// n = 3
// Expected outcome: 0101 1011 (91)
// Third scenario:
// x = 94 -> 0101 1110
// y = 195 -> 1100 0011
// p = 6
// n = 4
// Expected outcome: 1101 1110 (222)
printf("%d\n", setbits(100, 4, 3, 5));
printf("%d\n", setbits(94, 0, 3, 195));
printf("%d\n", setbits(94, 6, 4, 195));
return 0;
}