V
vortura
Hello all,
I've been working through some of the exercises in the K&R book, and I
think I might have found a bug in one of the answers on the CLC wiki.
Exercise 2-7 asks for a function, invert(x, p, n) that returns x with
the n bits starting at p inverted.
http://clc-wiki.net/wiki/K&R2_solutions:Chapter_2:Exercise_7
The answer listed on the wiki creates a mask of n 1's, then left
shifts them by p before xor'ing with x. By left shifting the mask by
p though, I think the mask is shifted past p, meaning the wrong bits
are inverted by the XOR. I think the correct solution would left
shift the mask by (p + 1 - n) instead. e.g.
unsigned invert(unsigned x, int p, int n) {
unsigned mask;
mask = ~(~0U << n) << (p + 1 - n);
return x ^ mask;
}
Is the answer in the wiki buggy, or have I made a mistake somewhere?
regards,
Richard
I've been working through some of the exercises in the K&R book, and I
think I might have found a bug in one of the answers on the CLC wiki.
Exercise 2-7 asks for a function, invert(x, p, n) that returns x with
the n bits starting at p inverted.
http://clc-wiki.net/wiki/K&R2_solutions:Chapter_2:Exercise_7
The answer listed on the wiki creates a mask of n 1's, then left
shifts them by p before xor'ing with x. By left shifting the mask by
p though, I think the mask is shifted past p, meaning the wrong bits
are inverted by the XOR. I think the correct solution would left
shift the mask by (p + 1 - n) instead. e.g.
unsigned invert(unsigned x, int p, int n) {
unsigned mask;
mask = ~(~0U << n) << (p + 1 - n);
return x ^ mask;
}
Is the answer in the wiki buggy, or have I made a mistake somewhere?
regards,
Richard