我的任務是搜索數字的二進制表示並替換數字的另一個二進制表示的匹配模式。如果我得到一個匹配,我將第一個整數的匹配位轉換爲零,然後繼續。 例如,數字469將是111010101
,我必須將其與5(101
)匹配。這是我迄今爲止編寫的程序。不按預期工作。匹配數字中的一系列位,然後將匹配轉換爲零?
using System;
namespace Conductors
{
class Program
{
static void Main(string[] args)
{
//this is the number I'm searching for a match in
int binaryTicket = 469;
//This is the pattern I'm trying to match (101)
int binaryPerforator = 5;
string binaryTicket01 = Convert.ToString(binaryTicket, 2);
bool match = true;
//in a 32 bit integer, position 29 is the last one I would
//search in, since I'm searching for the next 3
for (int pos = 0; pos < 29; pos++)
{
for (int j = 0; j <= 3; j++)
{
var posInBinaryTicket = pos + j;
var posInPerforator = j;
int bitInBinaryTicket = (binaryTicket & (1 << posInBinaryTicket)) >> posInBinaryTicket;
int bitInPerforator = (binaryPerforator & (1 << posInPerforator)) >> posInPerforator;
if (bitInBinaryTicket != bitInPerforator)
{
match = false;
break;
}
else
{
//what would be the proper bitwise operator here?
bitInBinaryTicket = 0;
}
}
Console.WriteLine(binaryTicket01);
}
}
}
}
我會建議這張發佈@ http://codereview.stackexchange.com/而不是SO。完整的代碼無法正常工作,因爲您期望在此處更好地進行審閱。 – Mikanikal
@Mikanikal CodeReview適用於*完成*的工作的完整代碼,但需要反饋以獲得更好/更清潔的解決方案。如果OP在codereview上發佈它,它將被關閉。 SO是這個問題的正確網站。然而,目前還不清楚「不按預期工作」可能意味着一百萬件不同的事情。 – Rob
@Rob這是我的意圖,如果它沒有聽起來(讀)。正在工作的代碼,但並不如預期,這意味着他需要更好的解決方案。因此,從OP中更清晰的問題,我想我會收回我的評論。 – Mikanikal