Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using this answer to this question in order to view the 0's in my binary value Byte to Binary String C# - Display all 8 digits

int a = 00010

and am converting it into a string with:

string b = Convert.ToString(a).PadLeft(5, '0');

This works perfectly and I can print 00010 instead of 10. However, I need to convert this back to an integer in order to populate an integer array. I am using this to convert it back into a integer:

int c = Convert.ToInt32(b);
Console.WriteLine(c);

Howwever, when I print this it the preceding 0's are missing, and I am printing '10'. Is there any way to convert this back to an integer and keep the preceding 0's? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

An integer doesn't have leading zeros. Integers are numeric values, they don't carry display information with them. So if you're storing the value as an integer then you're not storing any display information. In that case you apply the display information when you display the value:

int a = 10;
Console.WriteLine(Convert.ToString(a).PadLeft(5, '0'));

If you want the display information to be retained as part of the value itself, make it a string:

string a = "00010";
Console.WriteLine(a);

If it needs to be stored as an integer and you don't want to re-write the display logic many times, you can encapsulate that logic into a custom type which wraps the integer:

public class PaddedInteger
{
    private int Value { get; set; }
    private int PaddingSize { get; set; }
    private char PaddingCharacter { get; set; }

    public PaddedInteger(int value, int paddingSize, char paddingCharacter)
    {
        Value = value;
        PaddingSize = paddingSize;
        PaddingCharacter = paddingCharacter;
    }

    public override string ToString()
    {
        return Convert.ToString(Value).PadLeft(PaddingSize, PaddingCharacter);
    }
}

Then in your code:

PaddedInteger a = new PaddedInteger(10, 5, '0');
Console.WriteLine(a);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...