Sunday, February 12, 2012

Binary Bits - C# Version

Some years ago in EDN [1] I wrote about a set of Visual Basic routines that roughly paralleled the bit manipulation features that we enjoyed in C. Well folks, VB Classic is dead or at least has no future and we here at AnalogHome have long ago moved on to C# .NET which is a really powerful language.

Alas, C# still is missing some features that make for fast and easy hardware control. Specifically when programming SPI, I2C or other serial based devices we need to be able to rotate bytes or words and shift successive bits out for our hardware devices.

So as a follow on to that “Turn of the Century” article I have developed a set of routines that allow for shift right, shift left along with set get and clear a specific bit in any byte or word.

With these routines as a basis for your own code you can now easily manipulate individual bits in a byte or word and hopefully be faster at programming that hardware from your PC.

Bit manipulation routines included here,

Input: input_num can be any length 1 to 32 bits (but need to be cast to a UInt32)
bit: 0 = LSB, 1, 2 . . . 8 = MSB on 8 bit number, etc,
but not greater than 31 or the width of the input number

Return: Is either the state of the bit (For GetBit) or the new number after the operation is completed.

public static byte GetBit(UInt32 input_num, byte bit)
public static UInt32 SetBit(UInt32 input_num, byte bit)
public static UInt32 ClearBit(UInt32 input_num, byte bit)


The shift routines include,

Input: input_num: is an unsigned int of either 8, 16 or 32 bits in length.
Return: The bit shifted out
AND
The original number, shifted is returned as a reference parameter to the method.

public static byte ShiftRight_8(ref byte input_num)
public static byte ShiftRight_16(ref byte input_num)
public static byte ShiftRight_32(ref byte input_num)

public static byte ShiftLeft_8(ref byte input_num)
public static byte ShiftLeft_16(ref byte input_num)
public static byte ShiftLeft_32(ref byte input_num)


Some implementation notes: A C# purist would object to having different methods for different word sizes and it is true that these routines can be built that way (just as they can be built a million different ways) but I find that in my use it is easier to keep in mind what byte or word size I am working in and then using the appropriate shift routine. That's the way I think and it roughly parallels the way my embedded C compilers implement their shift routines.

[1] http://www.edn.com/article/505052-ActiveX_control_brings_bit_manipulation_to_Windows.php




No comments:

Post a Comment