From 7f92871abc1fcb69defa1d366c7b29cb1800b33c Mon Sep 17 00:00:00 2001 From: aQua Date: Tue, 24 Jul 2018 17:19:32 +0800 Subject: [PATCH] =?UTF-8?q?2.63=20=E4=BF=AE=E5=A4=8D=20srl-src.c=20?= =?UTF-8?q?=E4=B8=AD=E5=8F=82=E6=95=B0=20k=20=3D=3D=200=20=E6=97=B6?= =?UTF-8?q?=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在 C 语言中 x << s 实际上是 x << ( s%w ) ,其中 w 为 x 的位宽度。 所以,当 k == 0 时, -1 << (w-k) 并没有进行左移。 --- chapter2/code/srl-sra.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/chapter2/code/srl-sra.c b/chapter2/code/srl-sra.c index e7d0c4c8..85c257bf 100644 --- a/chapter2/code/srl-sra.c +++ b/chapter2/code/srl-sra.c @@ -9,7 +9,7 @@ unsigned srl(unsigned x, int k) { unsigned xsra = (int) x >> k; int w = sizeof(int) << 3; - int mask = (int) -1 << (w - k); + int mask = -1 << (w - k - 1) << 1; return xsra & ~mask; } @@ -17,7 +17,7 @@ int sra(int x, int k) { int xsrl = (unsigned) x >> k; int w = sizeof(int) << 3; - int mask = (int) -1 << (w - k); + int mask = -1 << (w - k - 1) << 1; //let mask remain unchanged when the first bit of x is 1, otherwise 0. int m = 1 << (w - 1); mask &= ! (x & m) - 1; @@ -32,10 +32,16 @@ int main(int argc, char* argv[]) { assert(sra(test_int, 4) == test_int >> 4); test_unsigned = 0x87654321; - test_int = 0x87654321; + test_int = 0x87654321; - assert (srl (test_unsigned, 4) == test_unsigned >> 4); - assert (sra (test_int, 4) == test_int >> 4); + assert (srl (test_unsigned, 4) == test_unsigned >> 4); + assert (sra (test_int, 4) == test_int >> 4); + + test_unsigned = 0xFFFFFFFF; + test_int = 0x80000000; + + assert (srl (test_unsigned, 0) == test_unsigned >> 0); + assert (sra (test_int, 0) == test_int >> 0); return 0; }