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 formatting an integer as a binary string representation (See related posts)

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

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


Click here to browse all 4857 code snippets

Related Posts