8

私は本当にこれに困惑しています。C# には、次のような 16 進数の定数表現形式があります。

int a = 0xAF2323F5;

バイナリ定数表現形式はありますか?

4

4 に答える 4

9

いいえ、C# にはバイナリ リテラルはありません。もちろん、Convert.ToInt32 を使用してバイナリ形式の文字列を解析することはできますが、それが優れたソリューションになるとは思いません。

int bin = Convert.ToInt32( "1010", 2 );
于 2009-08-07T20:26:35.803 に答える
3

C#7 以降、コードでバイナリ リテラル値を表すことができます。

private static void BinaryLiteralsFeature()
{
    var employeeNumber = 0b00100010; //binary equivalent of whole number 34. Underlying data type defaults to System.Int32
    Console.WriteLine(employeeNumber); //prints 34 on console.
    long empNumberWithLongBackingType = 0b00100010; //here backing data type is long (System.Int64)
    Console.WriteLine(empNumberWithLongBackingType); //prints 34 on console.
    int employeeNumber_WithCapitalPrefix = 0B00100010; //0b and 0B prefixes are equivalent.
    Console.WriteLine(employeeNumber_WithCapitalPrefix); //prints 34 on console.
}

詳細については、こちらをご覧ください

于 2016-12-16T23:30:05.467 に答える
2

拡張メソッドを使用できます。

public static int ToBinary(this string binary)
{
    return Convert.ToInt32( binary, 2 );
}

ただし、これが賢明かどうかは、あなたにお任せします (任意の文字列で動作するという事実を考えると)。

于 2009-08-07T20:44:01.307 に答える