I'm a noob reading The C Programming Language by Kernighan & Ritchie. I'm on section 2.9 and am able to do basic calculations using the bitwise operators, but I still don't understand why they have some of the effects that they do in the examples shown in the book. I have absolutely no clue whats going on in the last example.
I don't understand why this expression has that effect. Wouldn't n = 0; have the same effect? Or maybe n = ~0177;?Quote:
The bitwise AND operator & is often used to mask off some set of bits, for example
n = n & 0177;
sets to zero all but the low-order 7 bits of n.
What does x look like before the operation is performed. 16 0-bits or is it in some state I don't know about? And why is word length coming into this discussion out of nowhere?Quote:
x = x & ~077
sets the last six bits of x to zero. Note that x & ~077 is independent of word length, and is
thus preferable to, for example, x & 0177700, which assumes that x is a 16-bit quantity.
My brain collapsed.Quote:
As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p. We assume that bit position 0 is at the right end and that n and p are sensible positive values. For example, getbits(x,4,3) returns the three bits in positions 4, 3 and 2, right-adjusted.
The expression x >> (p+1-n) moves the desired field to the right end of the word. ~0 is all 1-bits; shifting it left n positions with ~0<<n places zeros in the rightmost n bits; complementing that with ~ makes a mask with ones in the rightmost n bits.Code:/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
I'm having a really hard time visualizing what's actualy happening here. Some help would really be appreciated. Thanks.