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

About this user

Owen Corpening

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Csharp format integer as hex string

// 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

Csharp formatting an integer as a binary string representation

// description of your code here

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.ConvertByteToBinaryString(i));
		}
		/// <summary>
		/// Format integer as a binary string with spaces between every 4 bits
		/// </summary>
		/// <param name="input">integer to format</param>
		/// <returns>string of the form "0000 0000 0000 0000 0000 0110 0001 1000"</returns>
		private string ConvertByteToBinaryString(long input)
		{
			string result = null;
			string bitstring = null;
			for(int i=31;i>=0;i--)
			{
				if (((input >> i) & 1) == 1) result = "1";
				else result = "0";
				bitstring += result;
				if ((i>0) && ((i)%4)==0)
				{
					bitstring += " ";
				}
			}
			return bitstring;
		}
	}
}

produces this output:
0000 0000 0000 0000 0000 0000 0000 1100
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS