Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - preceding 0's in integer value

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...