Use C# to Reverse the Bits in a System.Byte
During an employment search, some time back, I applied for a senior C++ opportunity at Kyocera Wireless, in San Diego. I was invited to the company's office to take a test. As a senior .NET architect and engineer, pretty much all of the tests with which I deal are performed by NUnit, not people. Nevertheless, the economy was in such a condition at that point that I went anyway. When I arrived, I soon observed that the foyer was quickly filling up with people - most of whom had obviously been in school quite recently. This collection of nameless potential "human resources" was efficiently [the best word I can find is] herded into a number of small offices to be given a timed test. Although I was supposedly under consideration for a senior object-oriented C++ position, the test was specifically targeted toward straight "C" hacks. I will not bore my valued readers with either the details or the results, other than to proclaim that I do not currently work at Kyocera. Neither would I ever be likely to work for a company that chooses to humiliate candidates in this manner.
I found one test question rather interesting, however. The examiner wanted us to write a "C" function to reverse the bits of a "C" char passed in as a parameter. Now, to someone like me, this request immediately throws up warning flags about things like sign bits, etc., but I will not go into that. For reference, here is a nice collection of C/C++ Bit Twiddling Hacks that includes several about reversing bit sequences. The one for Reverse an N-bit quantity in parallel in 7 * lg(N) operations was perhaps the most interesting.
Once safely at home, I threw together the very simplistic C# BitReverser class, below, to explore one way to reverse the bits in a System.Byte. BitReverser has a single static Reverse() method. I crafted some NUnit tests around it and BitReverser appears to work. Enjoy!
using System;
namespace JetUtils.ByteUtils
{
/// <summary>
/// BitReverser contains static methods to reverse bits. For now,
/// BitReverser reverses only the byte type. Future versions
/// may add functionality to reverse bits for objects from
/// other data types.
/// </summary>
public class BitReverser
{
public BitReverser()
{
}
/// <summary>
/// Reverse the bits in a byte
/// </summary>
/// <param name="inByte">byte</param>
/// <returns>byte</returns>
public static byte Reverse(byte inByte)
{
byte result = 0x00;
byte mask = 0x00;
for ( mask = 0x80;
Convert.ToInt32(mask) > 0;
mask >>= 1)
{
result >>= 1;
byte tempbyte = (byte)(inByte & mask) ;
if (tempbyte != 0x00)
result |= 0x80;
}
return (result);
}
}
}
|