Frage

There are some notations to write numbers in C# that tell if what you wrote is float, double, integer and so on.

So I would like to write a binary number, how do I do that?

Say I have a byte:

byte Number = 10011000 //(8 bits)

How should I write it without having the trouble to know that 10011000 in binary = 152 in decimal?

P.S.: Parsing a string is completely out of question (I need performance)

War es hilfreich?

Lösung

as of c# 6 c# 7 you can use 0b prefix to get binary similar to the 0x for hex

int x           = 0b1010000; //binary value of 80
int seventyFive = 0b1001011; //binary value of 75

give it a shot

Andere Tipps

You can write this:

int binaryNotation = 0b_1001_1000;

In C# 7.0 and later, you can use the underscore '_' as a digit seperator including decimal, binary, or hexadecimal notation, to improve legibility.

There's no way to do it other than parsing a string, I'm afraid:

byte number = (byte) Convert.ToInt32("10011000", 2);

Unfortunately you will be unable to assign constant values like that, of course.

If you find yourself doing that a lot, I guess you could write an extension method on string to make things more readable:

public static class StringExt
{
    public static byte AsByte(this string self)
    {
        return (byte)Convert.ToInt32(self, 2);
    }
}

Then the code would look like this:

byte number = "10011000".AsByte();

I'm not sure that would be a good idea though...

Personally, I just use hex initializers, e.g.

byte number = 0x98;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top