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-5 of 5 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

c C++ convert hex to ascii

// Presented with hex such as 0x12345abc perhaps there is a spot in there
// which represents an ascii char - such as 53 would be 'S'
// Common when dealing with hardware-related data structures and wire
// protocols

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

/*
*	To convert 53 to the character 'S':
*	char returnVal = hexToString('5', '3');
*/
char hexToAscii(char first, char second)
{
	char hex[5], *stop;
	hex[0] = '0';
	hex[1] = 'x';
	hex[2] = first;
	hex[3] = second;
	hex[4] = 0;
	return strtol(hex, &stop, 16);
}
int main(int argc, char* argv[])
{
	printf("%c\n", hexToAscii('5', '3'));
}

produces this output:
S

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

Csharp bitfields

// C# does not provide the ability to set a field within a byte to a value.
// It has the ability to set individual bits, but if you are accessing hardware
// you may need to set fields within bytes - no way jose. Until now!

/// <summary>
/// SetField is used to set a certain set of bits to the value specified.
/// </summary>
/// <param name="input">byte in which to set the field</param>
/// <param name="value">value to set field to</param>
/// <param name="location">bit number within byte where field begins</param>
/// <param name="noBits">field size</param>
private void SetField(ref long input, long value, byte location, int noBits)
{
	int size = 1;
	if ((location > 31) || (location < 0))
		throw new Exception("location out of range: " + location);
	if ((noBits > 31) || (noBits <= 0))
		throw new Exception("noBits out of range: " + noBits);
	if (noBits > 1) size = size << noBits;
	if ((value < 0) || (value > size))
		throw new Exception("value out of range: " + value);
	value = value << location;
	if (value < 0)
		throw new Exception("value out of range after shifting to field location: " + value);
	input = (input | value);
}


Test:
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 = 2; // 
			Console.WriteLine(t.ConvertByteToBinaryString(i));
			t.SetField(ref i,5,8,4);
			Console.WriteLine(t.ConvertByteToBinaryString(i));
		}
		/// <summary>
		/// SetField is used to set a certain set of bits to the value specified.
		/// </summary>
		/// <param name="input">byte in which to set the field</param>
		/// <param name="value">value to set field to</param>
		/// <param name="location">bit number within byte where field begins</param>
		/// <param name="noBits">field size</param>
		private void SetField(ref long input, long value, byte location, int noBits)
		{
			int size = 1;
			if ((location > 31) || (location < 0))
				throw new Exception("location out of range: " + location);
			if ((noBits > 31) || (noBits <= 0))
				throw new Exception("noBits out of range: " + noBits);
			if (noBits > 1) size = size << noBits;
			if ((value < 0) || (value > size))
				throw new Exception("value out of range: " + value);
			value = value << location;
			if (value < 0)
				throw new Exception("value out of range after shifting to field location: " + value);
			input = (input | value);
		}
		/// <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;
		}
	}
}


Output from test:
C:\>testApp.exe
0000 0000 0000 0000 0000 0000 0000 0010
0000 0000 0000 0000 0000 0101 0000 0010
C:\>
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS