Is there a way to assign a binary value to a VB variable? All of the obvious choices don't work. I've tried prefixing with &B
, appending with b
but nothing seems to work. I'm not having much luck searching for it either. I don't need this for my application, but I'm rather, just curious so alternate solutions are not necessary.
[Edit] For clarification, what I was looking for (which does not appear to be possible) was how to assign a literal binary number to a variable, in a similar manner in which you can assign a hex or octal number. I was just looking for a more visually engaging way to assign values to a flag enum.
Code:
Dim num as Integer = &H100ABC 'Hex'
Dim num2 as Integer = &O123765 'Octal'
Dim myFantasy as Integer = &B1000 'What I would like to be able to do'
Dim myReality as Integer = 2 ^ 3 'What I ended up doing'
To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. Note: To print value in binary format, we use bin() function.
Binary value can be assigned in a variable by using "0b" notation (we can say it format specifier too), this is a new feature which was introduced in C99 (not a standard feature, some compilers may not support this feature).
To specify a binary literal, add the prefix 0b or 0B to the integral value. So, we can express binary digits in a program by assigning them to variables, and the output of those variables after executing the program will be decimal digits.
In Python, using binary numbers takes a few more steps than using decimal numbers. When you enter a binary number, start with the prefix '0b' (that's a zero followed by a minuscule b). 0b11 is the same as binary 11, which equates to a decimal 3.
I might stab myself after this one:
Convert.ToInt32("1100101", 2);
On a more serious note (noticing that you have updated the question), for flag enums
what you may want is the left shift operator (<<
):
Dim myReality as Integer = 1 << 0 // 1
Dim myAlternateReality as Integer = 1 << 1 // 2
Dim myParallelUniverse as Integer = 1 << 2 // 4
...
and so on up to 31.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With