<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bitmatic &#187; bytes</title>
	<atom:link href="http://bitmatic.com/tag/bytes/feed" rel="self" type="application/rss+xml" />
	<link>http://bitmatic.com</link>
	<description>Lean IT-solutions in .NET/C#</description>
	<lastBuildDate>Tue, 11 Jan 2011 09:37:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>C-style unions in .NET</title>
		<link>http://bitmatic.com/c/c-style-unions-in-netc</link>
		<comments>http://bitmatic.com/c/c-style-unions-in-netc#comments</comments>
		<pubDate>Tue, 17 Feb 2009 00:09:16 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[bytes]]></category>
		<category><![CDATA[union]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=155</guid>
		<description><![CDATA[ByteUnion &#8211; Unions in .NET/C# Do you ever wonder what happened to the old-school C/C++ unions in C# ? Unions were extremely usefull for a wide range of problems back in the days where we dared make bold assumptions about memory-layout and the width of variables. .NET/C# does not allow us to make unions like [...]]]></description>
			<content:encoded><![CDATA[<h3> ByteUnion &#8211; Unions in .NET/C#</h3>
<p>Do you ever wonder what happened to the old-school C/C++ unions in C# ?<br />
Unions were extremely usefull for a wide range of problems back in the days where we dared make bold assumptions about memory-layout and the width of variables.</p>
<p>.NET/C# does not allow us to make unions like that directly anymore, but we can still achieve most of the functionality by explicitly controlling the layout of classes and structs in C#</p>
<h3> A tiny example</h3>
<p>The System.Runtime.InteropServices namespace has the tools to handle the layout of structs and classes. It allows you to define fields in structures in a way so they even overlap.<br />
This mechanism &#8211; when used with simple data types &#8211; can be used to simulate unions in C#.</p>
<p>Take a look at the following small class:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
[StructLayout(LayoutKind.Explicit)]
<span class="kwrd">public</span> <span class="kwrd">class</span> union
{
    [FieldOffset(0)] <span class="kwrd">public</span> <span class="kwrd">byte</span> lowbyte;
    [FieldOffset(1)] <span class="kwrd">public</span> <span class="kwrd">byte</span> highbyte;
    [FieldOffset(0)] <span class="kwrd">public</span> <span class="kwrd">ushort</span> word;
}
</pre>
<p>This is a very basic class containing only two bytes and a word. There are two very interesting things to note though.</p>
<ul>
<li>The whole class is given the &#8220;StructLayout(LayoutKind.Explicit)&#8221; attribute. This tells the compiler that we want to control the layout of the fields ourselves.</li>
<li>Each field is then given an offset with the &#8220;FieldOffset&#8221; attribute. This is where the magic happens. The 16-bit word is placed so it overlaps the two 8-bit bytes.</li>
</ul>
<h3>Using it&#8230;</h3>
<p>Now if you assign anything to the 16-bit word it will change the 2 bytes &#8211; and vice versa. The class can now be used like this:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
union u = <span class="kwrd">new</span> union();
u.word = 0x0102;

Console.WriteLine(<span class="str">"lowbyte is: "</span> + u.lowbyte);
Console.WriteLine(<span class="str">"highbyte is: "</span> + u.highbyte);</pre>
<p>The code will output:</p>
<pre class="console">
lowbyte is: 2
highbyte is: 1
</pre>
<h3>Practical applications</h3>
<p>I have used this class &#8211; in an expanded version &#8211; in several projects. In <a href="http://www.bitmatic.com/ekho" title="EKHO - CRT analysis equipment">EKHO</a> I use it to parse the input from the audio port. The data from that port is a byte-stream that contain pairs of bytes, that represent the 16-bit samples. In a project I have done for a company called <a href="http://www.kamstrup.dk">Kamstrup</a>, it is used to handle data recieved as byte arrays on a serial port.<br />
Generally &#8211; Whenever you have code that says something like &#8220;a = x*256 + y&#8221; or &#8220;b = (arr[0]<<8) + arr[1]" you can use a ByteUnion instead and greatly enhance readability.</p>
<h3>Additional functionality</h3>
<p>The ByteUnion class I have used in real-life projects is much more advanced than this tiny example. The real power of the class is only really obvious when the class is expanded with a constructor that take a byte array as an argument. Also adding stuff like comparison operators and a few interfaces really enhance the usability.<br />
I will return with that in a later post&#8230; Now I have work to do <img src='http://bitmatic.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/c/c-style-unions-in-netc/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

