Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Csharp format integer as hex string (See related posts)

// Using the built in ability to print a byte as a hex value
// this set of methods gives the ability to print shorts
// and longs as hex using the spacing that is customary.

using System;

namespace testApp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Class1 t = new Class1();
			long i = 12; // 
			Console.WriteLine(t.int32ToHexString(i));
		}

		private string int32ToHexString(long i)
		{
			byte[] int32Bytes;
			int32Bytes = BitConverter.GetBytes(i);
			return String.Format("{0}{1}{2}{3}",
				padString(int32Bytes[0].ToString("X")),
				padString(int32Bytes[1].ToString("X")),
				padString(int32Bytes[2].ToString("X")),
				padString(int32Bytes[3].ToString("X")));
		}

		private string int16ToHexString(short i)
		{
			byte[] int32Bytes;
			int32Bytes = BitConverter.GetBytes(i);
			return String.Format("{0}{1}",
				padString(int32Bytes[0].ToString("X")),
				padString(int32Bytes[1].ToString("X")));
		}

		private string byteToHexString(byte b)
		{
			return padString(String.Format("{0}", b.ToString("X")));
		}

		private string padString(string s)
		{
			while (s.Length < 2) s = "0" + s;
			while (s.Length < 3) s = " " + s;
			return s;
		}
	}
}



produces this output:
0C 00 00 00

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts