如何在C位方式XOR [英] How to make bit wise XOR in C

查看:173
本文介绍了如何在C位方式XOR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图进入C编程,和我有麻烦写一个按位异或函数只有&放大器; 运营商。例如: BITXOR(4,5)= 1 。我怎样才能做到这一点?

到目前为止,我有这样的:

  INT BITXOR(INT X,int y)对{    返回Z者除外;
}


解决方案

好吧,让我们想想这一点。什么是XOR办?

  X Y XOR
------------
0 0 0
1 0 1
0 1 1
1 1 0

那么,我们如何把它转换成一个功能?
让我们来思考和和的逆顺序和(〜X'放大器;〜y)的(这恰好是NOR):

 (〜X'放大器;〜Y)
 X Y和NOR
 ---------------------
 0安培; 0 = 0 1
 1和; 0 = 0 0
 0安培; 1 = 0 0
 1和; 1 = 1 0

看着那些两个输出,这是pretty接近,我们所要做的只是NOR两个previous输出(x和y)(X不Y),我们不得不解决方案!

 (A)(B)(A和B)
X和Y X不Y〜A和一b
-------------------------------
   0 1 0
   0 0 1
   0 0 1
   1 0 0

现在只写了:

  A =(X安培; Y)
B =(〜X'放大器;〜Y)
异或结果=(〜A和〜B)

BINGO!
现在只写到函数

  INT BITXOR(INT X,int y)对
{
    int类型的= X&放大器; ÿ;
    INT B =〜X'放大器; 〜ÿ;
    INT Z =〜A和一B;
    返回Z者除外;
}

I'm trying to get into C programming, and I'm having trouble writing a bitwise XOR function with only ~ and & operators. Example: bitXor(4, 5) = 1. How can I achieve this?

So far I have this:

int bitXor(int x, int y) {

    return z;
}

解决方案

Well, let's think about this. What does XOR do?

x   y    XOR
------------
0   0     0
1   0     1
0   1     1
1   1     0

So how do we turn that into a function? Let's think about AND, and the inverse order of AND (~x&~y) (this happens to be NOR):

              (~x&~y)
 x   y   AND    NOR   
 ---------------------
 0 & 0  = 0      1    
 1 & 0  = 0      0 
 0 & 1  = 0      0
 1 & 1  = 1      0

Looking at those two outputs, it's pretty close, all we have to do is just NOR the two previous outputs (x AND y) (x NOR y) and we'd have the solution!

  (a)       (b)    ( a NOR b )
x AND y   x NOR y    ~a & ~b
-------------------------------
   0         1          0
   0         0          1
   0         0          1
   1         0          0

Now just write that out:

a = ( x & y )
b = ( ~x & ~y )
XOR'd result = (~a & ~b)

BINGO! Now just write that into a function

int bitXor(int x, int y) 
{
    int a = x & y;
    int b = ~x & ~y;
    int z = ~a & ~b;
    return z;
}     

这篇关于如何在C位方式XOR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆