Home > Back-end >  C# Decimal To Binary
C# Decimal To Binary

Time:12-28

I'm learning little by little with your help. Thank you always.

i have a question. i know how to convert Decimal To binary ( convert.Tostring(2, 2); ) but result is 0010.

i want these result 0000 0010.

how can i convert this way??

static byte[] gbuff = new byte[1000];
...

string[] rxData = new string[31]

.....

    for(int x=0; x<31; x  )
    {
        rxData[x] = Convert.Tostring(gbuff[x], 2);
    }

I'm always grateful to everyone who helps me.

CodePudding user response:

Convert.ToString(2, 2).PadLeft(8, '0');

CodePudding user response:

Use an auxiliary method to convert numbers to binary form

static byte[] gbuff = new byte[1000];
...

string[] rxData = new string[31]
.....

for(int x=0; x<31; x  )
{
    rxData[x] = convertNumToBinary(Convert.ToInt32(gbuff[x]));
}

Convert method for numbers to binary

public string convertNumToBinary(int num)
{
    bool flag = true;
    Stack<int> myStack = new Stack<int>();
    while (flag)
    {
        int remaining = num % 2;
        myStack.Push(remaining);

        num = num / 2;


        if (num == 1)
        {
            flag = false;
            myStack.Push(num);
        }
    }

    string s = "";
    int len = myStack.Count;
    for (int i = 0; i < len; i  )
    {
       s  = myStack.Pop();
    }
    
    while(s.Length < 8)
    {
       s = "0"   s;
    }
    return s;
}
  • Related