This section is the practical implementation of Numeric Systems using C#.

NOTE: We are going to convert different Numeric Systems back and forth to the byte, if the value is larger than a byte you can convert it to an int.

In C# the decimal numeric system is used to represent a byte. A byte can take any number from 0 to 255:

byte fullByte = 255;

therefore a byte array is simply an array of numbers less than or equal to 255 each.

byte[] byteArray = new byte[]{ 65, 66, 67 };
byte byteFromHexadecimal = (byte)Convert.ToInt32("A5",16);
string hexadecimalFromByte = Convert.ToString(165, 16);
byte byteFromHexadecimalOption2 = (byte)int.Parse("A5", NumberStyles.HexNumber);
string hexadecimalFromByteOption2 = 165.ToString("X2");
byte byteFromBinary = (byte)Convert.ToInt32("10100101", 2);
string binaryFromByte = Convert.ToString(165, 2);

Conditions with binary

Look at the code below. Then we will look at how using AND/OR with ints/bytes work.

int and1 = (5 & 6); // result = 4
int and2 = (2 & 6); // result = 2
int or1 = (5 | 6); // result = 7
int or2 = (2 | 6); // result = 6

These results may seem a bit weird and thats because it's actually calculated from their binary values. 5 = 101 and 6 = 110

now we can compare the ints because: 1 = true and 0 = false

First column: 1(true) AND 1(true) = 1(true)

Second column: 0(false) AND 1(true) = 0(false)

Third column: 1(true) AND 0(false) = 0(false)

As a result we get "100" which is 4 in binary

First column: 1(true) OR 1(true) = 1(true)

Second column: 0(false) OR 1(true) = 1(true)

Third column: 1(true) OR 0(false) = 1(true)

As a result we get "111" which is 7 in binary

Bit Shifting

Think about some empty place holders with a single 1 bit amongst them.

010

If we move that bit one space to the left, we have left bit shifted 1.

100

If we move that bit one space to the right, we have right bit shifted 1.

001

Bit shifting in C# is easy. NOTE: change the 1 to bit shift more than one space.

int bitShiftLeft = 5 << 1;
int bitShiftRight = 5 >> 1;

Example of conditions with Bit shifting

As an example lets create a method to convert an int to a binary string.

public string IntToBinary(int number)
{
    var binary = "";
    while (number > 0)
    {
        binary = (number & 1) + binary;
        number = number >> 1;
    }
    return binary;
}

Since 1 in binary only occupies the first bit and has all 0s to the left (...0001), any number which gets AND compared to it will always return 0s for all the bits to the left because anything AND 0 always = 0. Only the first number may be a 1 or 0. So we can easiy determine the first place holder of a number using an AND conditional against 1.

1010101 AND
0000001
_______
0000001

We can then bit shift 1 to the right so that we can check the next bit in our number. We continue to loop through in this way until we have covered every bit.

1010101 >> 1 =
0101010

Check out these links for more info:

My C# language repo