How to convert an integer to fixed length hex string in C#?

前端 未结 3 1295
北恋
北恋 2020-12-16 14:13

I have an integer variable with max value of 9999.

I can convert to fixed length string (4-characters):

value.ToString(\"0000\");

a

相关标签:
3条回答
  • 2020-12-16 14:22
    String.Format( "{0:X2}", intValue)
    
    0 讨论(0)
  • 2020-12-16 14:37

    Here is another method, You can define a function and pass it 2 values, one the actual number and the second is the max length to fix. i.e.

    public string FixZero(string str, int maxlength)
    {
        string zero = "000000000000000000000000000000000000000";
        int length = str.Length;
        int diff = maxlength- length;
        string z = zero.Substring(1, diff);
        z = z + str;
        return z;
    }
    

    you need integers in the format 0012, FixZero("12", 4) or for 0001234, FixZero("1234", 7)

    0 讨论(0)
  • 2020-12-16 14:45

    Use a number after the X format specifier to specify the left padding : value.ToString("X4")

    0 讨论(0)
提交回复
热议问题