私は本当にこれに困惑しています。C# には、次のような 16 進数の定数表現形式があります。
int a = 0xAF2323F5;
バイナリ定数表現形式はありますか?
私は本当にこれに困惑しています。C# には、次のような 16 進数の定数表現形式があります。
int a = 0xAF2323F5;
バイナリ定数表現形式はありますか?
いいえ、C# にはバイナリ リテラルはありません。もちろん、Convert.ToInt32 を使用してバイナリ形式の文字列を解析することはできますが、それが優れたソリューションになるとは思いません。
int bin = Convert.ToInt32( "1010", 2 );
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.
}
詳細については、こちらをご覧ください。
拡張メソッドを使用できます。
public static int ToBinary(this string binary)
{
return Convert.ToInt32( binary, 2 );
}
ただし、これが賢明かどうかは、あなたにお任せします (任意の文字列で動作するという事実を考えると)。