问题
I have two input integer numbers and an output list< int> myoutputlist. My inputs are lets say
A=0x110101
B=0x101100
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 010010 (1 represents changing values; second and fifth bits should be changed in this case)
As C integer has value "1" for two times; there should be 2 results in this case
result 1-Changing only second bit, other bits are same as A(0x110101) :
Change second bit of A => D1=1101 1 1
result 2-Changing only fifth bit, other bits are same as A(0x110101) :
Change fifth bit of A => D2=1 1 0101
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);
}
}
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?
回答1:
I hope I understood your question right.
You are looking for the XOR operator.
C = A ^ B
A 110101
B 101100
--------
C 011001
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 |
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;
}
来源:https://stackoverflow.com/questions/29087434/c-sharp-fast-way-to-compare-2-integers-bit-by-bit-and-output-for-more-than-o