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 

C convert buffer to binary string

// Sometimes one wants to see data in binary
// This method converts an arbitrary buffer to 1's and 0's

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

char *getBufferAsBinaryString(void *in)
{
	int pos=0;
	char result;
	char bitstring[256];
	memset(bitstring, 0, 256);
	unsigned int *input= (unsigned int *)in;
	for(int i=31;i>=0;i--)
	{
		if (((*input >> i) & 1)) result = '1';
		else result = '0';
		bitstring[pos] = result;
		if ((i>0) && ((i)%4)==0)
		{
			pos++;
			bitstring[pos] = ' ';
		}
		pos++;
	}
	return bitstring;
}
int main(int argc, char* argv[])
{
	int i=53003;
	char buffer[1024];
	char *s=getBufferAsBinaryString(&i);
	strcpy(buffer, s);
	printf("%s\n", buffer);
}


produces this output:
0000 0000 0000 0000 1100 1111 0000 1011

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