Question

So, I'm familiar with GCC 0b00010010 for example to write a binary constant. How do I do that in .NET? I'm mainly concerned with VB C# and C++ as I'm debugging/modifying code in those languages.

If there isn't a direct way to do this, is there a short route that won't be impossible to read and modify later?


Code added to illustrate reason for question:

<FlagsAttribute( )> _
Enum ControlTypeEnum as Short
                    ‘   5 4 S 3 2 1 M L
    None = 0        ‘0x 0 0 0 0 0 0 0 0
    Lathe = 1       
    Mill = 2        
    P100 = 4        '*
    P200 = 8        '*
    P300 = 16       
    P300L = 17      '*
    P300SLP = 49    '*
    P300M = 18      '*
    P300SMP = 50    '*
    P400L = 65      '*
    P400SLP = 97    '*
    P400M = 66      '*
    P400SMP = 98    '*
End Enum

'Values with asterisk are valid return values from function
Was it helpful?

Solution 2

I'd prefer the following:

None = 0                       = 0
Lathe = 1                      = 1
Mill = 2                       = 1<<1
P100 = 4                       = 1<<2
P200 = 8                       = 1<<3
P300 = 16                      = 1<<4
S    = 32                      = 1<<5
P400 = 64                      = 1<<6

... and then, in your code later on, using P400 & Lathe & Mill instead of an extra constant P400LM. (depending on what you like better, use the decimal or bitshift representations of the powers of two.)


If you already have a huge bunch of code depending on those enums and don't want to refactor, you could use

P400LM = 1<<6 | 1<<1 | 1<<0

which makes it clear what this flag is a combination of (much clearer than 67, in my opinion.)

OTHER TIPS

The closest you might be able to do in C# is define it as a string and use Convert.ToInt (or etc.)

 var flags = Convert.ToInt32( "00010010", 2 );

Which is functional, but verbose and pretty bleh. You might (if you are crazy) consider an extension method

public static class Extensions
{
    public static Int32 toInt(this string me)
    {
        return Convert.ToInt32(me, 2);
    }
}
(...)
var myflags = "00010010".toInt();
(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top