2

i want to convert Decimal numbers to binary, Currently I'm using this way

private string strtoBin(string input)
{
    int number = Convert.ToInt32(input) ;
    string res = Convert.ToString(number, 2);

    return res;
}

it's working but when I'm having for example "6" I'm getting 110 instead of 0110? Any tips?!

6
  • 1
    "6" I'm getting 110 instead of 0110 Why not 00000110 or ... Commented Nov 7, 2014 at 19:24
  • My bad, only 4 bits not more :) 0110 @HamletHakobyan Commented Nov 7, 2014 at 19:26
  • 4
    res = res.PadLeft(4,'0') Commented Nov 7, 2014 at 19:27
  • See stackoverflow.com/questions/4829366/… Commented Nov 7, 2014 at 19:28
  • See stackoverflow.com/questions/6758196/… Commented Nov 7, 2014 at 19:37

1 Answer 1

3

Simple string modification:

string res = Convert.ToString(number, 2);
res = new string('0', 8 - res.Length) + res;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.