What is the data type for binary values? Is it a string data type?

What data type is binary ( 1

and 0

))? In one example, I saw that they have a string as data type.

From this I know that strings are not used for variables on which calculations are performed.

So when two binary variables are of a string data type and they work together, how do you do this?

+3


source to share


2 answers


There is no binary data type. There is one class that allows you to handle the BitVector32 bits

Or, you can just convert the binary value from string

(text) toint

//                           binary    , base
int binary = Convert.ToInt32("00000101", 2);

      




You can create a class Binary

if you really want, and then overload the operators, something like this:

public class Binary
{
    private int value;

    public Binary(int value)
    {
        this.value = value;
    }

    public static implicit operator Binary(string b)
    {
        return new Binary(Convert.ToInt32(b, 2));
    }

    public static explicit operator int(Binary b)
    {
        return b.value;
    }

    public static Binary operator +(Binary a, Binary b)
    {
        return new Binary(a.value + b.value);
    }
}

      

And then you have

Binary bin1 = "0001"; // 1
Binary bin2 = "0010"; // 2

Binary result = bin1 + bin2; // 3

int integerResult = (int)result; // 3

      

+4


source


Thanks for the clarification. When you converted a binary value to a string, you gave up the direct ability to multiply, since the values ​​are no longer numeric (same reason that string s = "3" * "4";

won't work either). You will need to convert the values ​​to a numeric data type to perform a mathematical operation, and then return to the string for display.



string b1 = Convert.ToString(3, 2);
string b2 = Convert.ToString(4, 2);
string product = Convert.ToString(Convert.ToInt32(b1, 2) * Convert.ToInt32(b2, 2), 2);
Console.WriteLine(product); // 
Console.WriteLine(Convert.ToInt32(product, 2));

      

0


source







All Articles