0

I am trying to convert values of type int32 of variable size to a hex string with minimal length and 0 padding.

Example: 434 = 01 B2

There are several C# ways, but they all have fixed size, depending on the value type, (Example: Int32 will always give a 4 bytes value like 00 00 00 01 for the number 1).

One can write a code to do it, but I assume there is a shorter way.

thanks

samtal

samtal
  • 131
  • 2
  • 12
  • Are the spaces in hex string necessary? – WAKU Dec 14 '13 at 11:51
  • Spaces are not functionally required, but they make it more readable for debugging and maintenance. Can be left out if it makes a difference. – samtal Dec 14 '13 at 12:44

3 Answers3

1
int x = 434;
string s = x.ToString("X").PadLeft(5,'0');

This will produce , 001B2

crypted
  • 10,118
  • 3
  • 39
  • 52
  • Thanks, but this is the easy (and wrong) way, and it does not answer my question. I have a **variable** value. can be 1, can be 163158, which can be 1 byte or 3 (for 163158 = 02 7D 56). the PadLeft(5,'0') dictates 5 chars. Besides, Hex bytes must be odd number chars, not 5. I need a solution that will only show the minimum necessary full hex bytes (each 2 chars, padded 0 left), but no padding to the whole number (like 00 00 00 01 for 1). – samtal Dec 14 '13 at 10:51
  • Sorry, I had an error in the prev comment. I meant "Hex bytes must be **EVEN** number chars", – samtal Dec 14 '13 at 14:46
1

Well, Int3 ὰ's answer is close, just need a further EVEN number handling:

int x = 434;
string s = x.ToString("X");
s = s.Length % 2 == 0 ? s : "0" + s;

About the spaces issue, I didn't figure out a very simple way, however, you can look at this

Community
  • 1
  • 1
WAKU
  • 290
  • 3
  • 17
0

Thanks WAKU for the missing part that was s = s.Length % 2 == 0 ? s : "0" + s; I solved the space (or any char) by byte iteration and double padding as follows: (Not really clean but working)

    int i; string d;
        long x = 258458685;
        string s = x.ToString("X");
        s = s.Length % 2 == 0 ? s : "0" + s;
        for (i = 0; i < s.Length  ; i = i + 2)
        {
            d = s.Substring(i ,2);
            Console.Write(d.PadLeft(2, '0').PadLeft(3,' '));
        }

Result: 0F 67 C4 3D

samtal
  • 131
  • 2
  • 12