用位运算实现简单的加减法~
以前不怎么理解怎么用位运算进行加减乘除运算,现在可以理解加减运算了,并且自己弄了个出来(乘除或者也可以自己弄出来,但感觉还需要一段时间整理,就先不弄了)~现在看上去个人感觉很容易理解,就是不知道其他人能理解多少了,看到下面代码后,是感觉不知道在说啥,还是了解个大概,还是像看到家一样熟悉?这就看对编程有多少感觉了~
其实,至少之前不理解的,现在就是自己弄了一下,就能了解个大概,然后稍微弄一下,代码出来了,就像看到家一样熟悉了……就拿出来做个标记吧~

#include<stdio.h> unsigned un_add( unsigned,unsigned ); int add( int,int ); int sub( int,int ); int main( void ) { const unsigned a=6; const unsigned b=4; const int c=3; const int d=-5; const int e=7; const int f=5; printf("%u+%u=%u\n",a,b,un_add(a,b)); printf("%d+%d=%d\n",c,d,add(c,d)); printf("%d-%d=%d\n",e,f,sub(e,f)); printf("%d-%d=%d\n",f,e,sub(f,e)); return 0; } unsigned un_add( unsigned a,unsigned b ) { unsigned c; do { c=(a&b)<<1; a^=b; }while (b=c); return a; } int add( int a,int b ) { return ( int )un_add(( unsigned )a,( unsigned )b); } int sub( int a,int b ) { return add(a,-b); }
再说一些小感受~有些时候,不懂的就算看了资料顶多就了解过大概……这个以前曾经花了很多时间去弄,但怎么也弄不出来,然后后来看了一下资料,按照资料方法弄了一遍,虽然能运行出来,但就是不知道资料在干些什么……然后某一天突然发现,原来自己不看资料也能像看到家一样熟悉~就是有种只可意会,不可言传的感觉

[此贴子已经被作者于2018-5-14 22:41编辑过]