2012-03-28 65 views
2

我一直在阅读Kernighan和Ritchie的“The C Programming Language”。解释包含按位运算符的C语句的工具

我发现它很难通过部分得到2.9位运算符

具体做法是:

练习2-6编写一个函数setbits(X,P,N,Y),其回报x,其中 n位开始于位置p设置为y的最右边的n位, 保持其他位不变。

有一个聪明的叫做理查德希思菲尔德的小伙子练习here的答案。

理查德的回答是:

return (x & ((~0 << (p + 1)) 
      | (~(~0 << (p + 1 - n))))) 
    | ((y & ~(~0 << n)) << (p + 1 - n)); 

问题

有谁知道一个工具,将解释的代码行类似上面的?

我希望存在类似于各种在线正则表达式解释器,但对于按位操作。

+0

像堆栈溢出的人的工具吗? ;) – Shahbaz 2012-03-28 15:31:44

+8

铅笔和纸张? – 2012-03-28 15:32:18

+1

我不认为有一种工具可以解析位运算符表达式并向您解释。您很可能必须阅读每位运营商以了解代码背后的含义。请查看以下链接http://www.cprogramming.com/tutorial/bitwise_operators.html,并一次性完成各部分内容,并尝试用简单的英语(或您选择的语言)向自己解释,以确保您了解 – 2012-03-28 15:33:41

回答

2

让我们让这个人可读吗?

Xÿp,和Ñ输入

temp1中TEMP2TEMP3,和结果等于零

let temp1等于p加1
temp1中等于0一的补左移temp1中
temp1中等于的位与Xtemp1中

左让temp2等于p加1减去n
TEMP2等于0的补数左移TEMP2
TEMP2是等于TEMP2

一的补离开让temp1中是等于位或temp1目录TEMP2

TEMP3等于p加1减去ñ

TEMP2等于0的补数左移ň
离开让TEMP2是等于TEMP2
一补,让TEMP2等于按位与的ÿTEMP2

TEMP2等于TEMP2左移TEMP3
离开让结果等于位或的temp1中TEMP2

来源:我的大脑。

从本C代码(从OP扩大):

int setbits(int x, int p, int n, int y) 
{ 
    int result = 0; 

    // evaluate the expression 
    { 
     int temp1 = 0; 
     int temp2 = 0; 
     int temp3 = 0; 

     temp1 = p + 1; 
     temp1 = ~0 << temp1; 
     temp1 = x & temp1; 

     temp2 = p + 1 - n; 
     temp2 = ~0 << temp2; 
     temp2 = ~temp2; 

     temp1 = temp1 | temp2; 

     temp3 = p + 1 - n; 

     temp2 = ~0 << n; 
     temp2 = ~temp2; 
     temp2 = y & temp2; 

     temp2 = temp2 << temp3; 
     result = temp1 | temp2; 
    } 

    assert(result == ((x & ((~0 << (p + 1))| (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n)))); 

    return result; 
} 
+0

这并不能解释任何事情。或者那是重点? – 2012-03-28 15:56:57

+0

@OliCharlesworth他只是要求解释,他已经知道代码做了什么,这只是帮助他理解它是如何工作的。 – 2012-03-28 15:58:19

+1

这解释了每个操作的作用,而不是它的工作原理。 – 2012-03-28 16:05:30