Reputation: 131
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
Upvotes: 0
Views: 1233
Reputation: 131
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
Upvotes: 0
Reputation: 349
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
Upvotes: 1
Reputation: 10306
int x = 434; string s = x.ToString("X").PadLeft(5,'0');
This will produce , 001B2
Upvotes: 1