[整理]在C中操作int的连续某几位
翻同事的The C Programming Language 2th(C程序设计语言)和对应的习题解答The C Answer Book看到的。
实体书看得爽,但写文章还是得找电子版,英文的chm有,可惜习题解答没文字版……
The shift operators < < and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand, which must be non-negative. Thus x < < 2 shifts the value of x by two positions, filling vacated bits with zero; this is equivalent to multiplication by 4. Right shifting an unsigned quantity always fits the vacated bits with zero. Right shifting a signed quantity will fill with bit signs (``arithmetic shift'') on some machines and with 0-bits (``logical shift'') on others.
The unary operator ~ yields the one’s complement of an integer; that is, it converts each 1-bit into a 0-bit and vice versa. For example
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. The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.
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.
/* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 < < n); }
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<
Exercise 2-6. 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.
unsigned setbits(unsigned x, int p, int n, unsigned y) { return (x & ((~0 < < (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n)); }
下面这个比较快:
unsigned setbits(unsigned x, int p, int n, unsigned y) { return x & ~(~(~0 < < n) << (p+1-n)) | (y & ~(~0 << n)) << (p+1-n)); }
MoeFan (萌番)
近期评论