How do I type literal binary in VB.NET?

时光怂恿深爱的人放手 提交于 2019-12-10 03:34:33

问题


How do you type binary literals in VB.NET?

&HFF          // literal Hex -- OK
&b11111111    // literal Binary -- how do I do this?

回答1:


You could define it as string and then parse it:

myBin = Convert.ToInt32("1010101010", 2)



回答2:


As of VB.NET 15 there is now support for binary literals:

Dim mask As Integer = &B00101010

You can also include underscores as digit separators to make the number more readable without changing the value:

Dim mask As Integer = &B0010_1010



回答3:


Expanding on codymanix's answer... You could wrap this in an Extension on Strings, and add type checking...
something along the lines of:

<Extension> Public Function ParseBinary(target As String) As Integer  
    If Not RegEx.IsMatch(target, "^[01]+$") Then Throw New Exception("Invalid binary characters.")  

    Return Convert.ToInt32(target, 2)  
End Function

This allows then, anywhere you have a string of binary value, say "100101100101", you can do:

Dim val As Integer = "100101100101".ParseBinary()  

Note that to use <Extension>, you must import System.Runtime.CompilerServices, and be running on Framework 3.5 or later.




回答4:


You don't.

VB.NET supports decimal (without prefix), octal (with &O prefix), and hexadecimal (with &H prefix) integer literals directly.



来源:https://stackoverflow.com/questions/1417662/how-do-i-type-literal-binary-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!