views:

298

answers:

3

How do you type binary literals in VB.NET?

&HFF          // literal Hex -- OK
&b11111111    // literal Binary -- how do I do this?
+3  A: 

You don't.

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

Mehrdad Afshari
+3  A: 

You could define it as string and then parse it:

myBin = Convert.ToInt32("1010101010", 2)
codymanix
+2  A: 

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.

eidylon
That looks mighty useful. Makes me wish I could upgrade to 3.5
David Rutten
Yah, between Extensions, LINQ and XML literals, ... 3.5 blows away 2.0! :)
eidylon