本文介绍了C#-快速比较两个整数的方式,逐位比较,并输出多个整数,可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个输入整数和一个输出列表. int> myoutputlist.我的输入是说
A = 0x 110101
B = 0x 101100

I have two input integer numbers and an output list< int> myoutputlist. My inputs are lets say
A=0x110101
B=0x101100

然后我根据A和B的数字计算出一个C整数,我已经对其算法进行了编码,我可以计算C整数. C整数显示应更改的位. 1值表示变化的位,0值表示不变的位.每次只应更改一位.由于C整数取决于A和B输入,因此有时需要更改1位,有时3位,有时8位.在给定的A和B值下,我的C整数如下

then I have calculated a C integer number depending on A and B numbers.I already coded its algorithm, I can calculate C integer. C integer shows which bits should be changed. 1 value represents changing bits, 0 values represents unchanging bits. Only one bit should be changed in each time. As C integer depends on A and B inputs, sometimes 1 bit, sometimes 3 bits, sometimes 8 bits needs to be changed. In this given A and B values, I have C integer as follows

C = 0x 0 1 00 1 0(1表示更改的值;在这种情况下,应更改第二和第五位)

C=0x 010010 (1 represents changing values; second and fifth bits should be changed in this case)

由于C整数具有两次"1"值;在这种情况下,应该有2个结果

As C integer has value "1" for two times; there should be 2 results in this case

结果1-仅更改第二个位,其他位与A(0x110101)相同:
更改A的第二位=> D1 = 1101 1 1

result 1-Changing only second bit, other bits are same as A(0x110101) :
Change second bit of A => D1=1101 1 1

结果2-仅更改第五位,其他位与A(0x110101)相同:
更改A的第五位=> D2 = 1 1 0101

result 2-Changing only fifth bit, other bits are same as A(0x110101) :
Change fifth bit of A => D2=1 1 0101

我在想的是使用for循环,逐步将A和C移位,并使用& 1掩码转换为C?并检查它是否等于"1"

What I am thinking is using a for loop, shifting A and C step by step, and using &1 mask to C? And check if it is equal to "1"

for(i=0;i<32;i++)
{int D=(C>>i)&1;     //I tried to check if i.th value is equal to 1 or not
 if(D==1)
   {   int E=(A&(~(2^i))) | ((2^i)&(~B)) //in first brackets, I removed i.th bit of A, then replaced it with "not B" value.
       myoutputlist.add(E);
   }
}

我需要做很多计算,但是令人不安的问题是我需要检查(D == 1)32次.我将使用它数百万次,有些计算大约需要2分钟.我正在寻找一种更快的方法.有什么主意,把戏吗?

I need to do lots of calculations but disturbing issue is that I need to check (D==1) for 32 times. I will use it many million times, some calculations take about 2 mins. I am looking for a faster way. Is there any idea, trick?

推荐答案

我希望我正确理解了您的问题.

I hope I understood your question right.

您正在寻找 XOR 运算符.

C = A ^ B

A 110101
B 101100
--------
C 011001

如果两个输入不同",

XOR 将始终为1.参见:

XOR will always be 1 if the two inputs are "different". See:

| A | B | XOR |
|---+---+-----|
| 0 | 0 |  0  |
| 0 | 1 |  1  |
| 1 | 0 |  1  |
| 1 | 1 |  0  |

然后您将可以像这样循环遍历C的位:

Then you will be able to loop through the bits of C like this:

for (int i = 0; i < 32; i++)
{
    bool bit = (C & (1 << i)) != 0;
}

这篇关于C#-快速比较两个整数的方式,逐位比较,并输出多个整数,可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:20