how do i convert a number (long, int, etc.) to a hex string?

In the Java (and, well, J#) world there is toHexString, but it’s not around in the BCL for C#/VB/etc. to use – so what’s available?

Well, if you’re good to go with big-endian byte ordering (and you should be, it reads easier!) then you can really just ToString with the hex format:

myLong.ToString(“X16”);
myInt.ToString(“X8”);

What if you wanted to print them out, but a byte at a time? Or, more generally, what if you wanted to print a byte array as a hex string? For getting them into byte arrays, BitConverter has GetBytes (much like String does) which gets most of your primitive types into a byte array: http://msdn2.microsoft.com/en-us/library/system.bitconverter.getbytes

Once you have a byte array that you want to spit out in the de-ad-be-ef kind of format, you only need to call BitConverter’s ToString methods, which are made for taking byte arrays:

http://msdn2.microsoft.com/en-us/library/3a733s97

Advertisements