pad 8 digit binary number representations - in C#

string binValue = Convert.ToString(64, 2);

But I need to show all 8 digits.

So

  string binValue = Convert.ToString(6, 2);

which would normally be "110" would need to be shown as:

00000110


How?

Thanks!!!  :)
LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?
 
BuggyCoderConnect With a Mentor Commented:
           var binStr = Convert.ToString(2, 2);
            
            var sb = new StringBuilder();
            for(int i=0;i<8-binStr.Length;i++)
            {
                sb.Append("0");
            }

            sb.Append(binStr);

Open in new window

0
 
Tom KnowltonWeb developerAuthor Commented:
... is what I ended up doing as well.

Thanks,

Tom

Q:  .NET does not provide a cleaner way to do this?

Something like, "I am representing this value as an 8-bit binary.  I want each digit to be represented, even if it is OFF (1 would be "00000001", 64 would be "10000000")"

Without having to "brute force" pad the difference with "0"?
0
 
BuggyCoderCommented:
well this is default behaviour, any leading zeros are ripped off....
0
 
Tom KnowltonWeb developerAuthor Commented:
ok

:)
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
string binValue = Convert.ToString ( 6, 2 ).PadLeft ( 8,'0' );
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.