在c#二进制字符串中查找特定的位值

时间:2012-08-09 21:33:51

标签: c# binary

是否有任何解决方案可以在二进制数的字符串表示中找到特定的二进制位值? 例如,我有一个64位长度的二进制字符串:

0000000000000000000000000001000000000000000000100001001000000000

我需要从左边开始查找并返回第28位的值。在上面的示例中,它等于1

4 个答案:

答案 0 :(得分:2)

int val = s[28 - 1] - '0';  ///////

答案 1 :(得分:1)

嗯,28左侧左侧的值是2^36位(64-28)的64

所以只需使用您的值制作二元&,如果它已更改,则表示左侧28的{​​{1}}为0,如果不是1

long value = ... 
//binary rapresentation value is (say) 

0000000000000000000000000001000000000000000000100001001000000000

所以,如果

if(value & 2^36 != value) //binary AND 
    return 0; //28th was 0
else
    return 1; //28th was 1

如果这不是您所要求的,请澄清。

答案 2 :(得分:1)

这可能是一个语言障碍,但这听起来像indexOf的好地方?如果您需要获取字符串的特定部分,我可以这样做:

//string array for example
foreach(string BinaryString in BinaryStrings[])
{
  string TwentyEightBitSub = BinaryString.SubString(28);
  if(TwentyEightBitSub.indexOf("00000010") != -1)
  {
    //do something with matched string 
  }

}

答案 3 :(得分:0)

如果你总是知道字符串是64位(前导零从不缺席),那么这将有效:

private int getBit(string binString, int index) {
    if (binString == null)
        throw new ArgumentNullException("binString");
    if (binString.Length != 64)
        throw new ArgumentException("binString was not of length 64.", "binString");
    if (index < 0 || index > 63)
        throw new ArgumentException("index was not in [0,63]", "index");

    char theBit = binString[binString.Length - (1 + index)];
    if (theBit == '0')
        return 0;
    else if (theBit == '1')
        return 1;
    else
        throw new ArgumentException("The supplied string was not binary.", "binString");
}