C# 二进制常量表示

发布于 2024-07-30 06:34:45 字数 114 浏览 4 评论 0原文

我真的被这个难住了。 在 C# 中,有一种十六进制常量表示格式,如下所示:

int a = 0xAF2323F5;

是否有二进制常量表示格式?

I am really stumped on this one. In C# there is a hexadecimal constants representation format as below :

int a = 0xAF2323F5;

is there a binary constants representation format?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不及他 2024-08-06 06:34:45

不,C# 中没有二进制文字。 您当然可以使用 Convert.ToInt32 解析二进制格式的字符串,但我认为这不是一个很好的解决方案。

int bin = Convert.ToInt32( "1010", 2 );

Nope, no binary literals in C#. You can of course parse a string in binary format using Convert.ToInt32, but I don't think that would be a great solution.

int bin = Convert.ToInt32( "1010", 2 );
谁人与我共长歌 2024-08-06 06:34:45

从 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.
}

可以找到更多信息 此处

As of C#7 you can represent a binary literal value in code:

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.
}

Further information can be found here.

抱猫软卧 2024-08-06 06:34:45

可以使用扩展方法:

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

但是,这是否明智我将由您决定(考虑到它可以对任何字符串进行操作)。

You could use an extension method:

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

However, whether this is wise I'll leave up to you (given the fact it will operate on any string).

无需解释 2024-08-06 06:34:45

自 Visual Studio 2017 起,支持像 0b00001 这样的二进制文字。

Since Visual Studio 2017, binary literals like 0b00001 are supported.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文