Posted By

pckujawa on 07/14/09

Statistics

Viewed 1854 times
Favorited by 0 user(s)

Convert a binary coded decimal (BCD) string into bytes

/ Published in: C#

BCD is where the hex value of a byte represents two integer values between zero and nine; e.g., 0x98 -> "98" (whereas its integer value is actually 152). The method throws an exception if non-BCD data is input.

You can also check out the partner method, [Convert bytes into a binary coded decimal (BCD) string](http://snipplr.com/view/16802/convert-bytes-into-a-binary-coded-decimal-bcd-string/).

Update:
Unfortunately, there doesn't seem to be a built-in method for doing this (there is for the converse; see System.BitConverter.ToString). The System.BitConverter.GetBytes(char) overload returns the byte value of the character, rather than a BCD byte array (`BitConverter.GetBytes('A')` returns a byte array holding `[65, 0]`, not [0x0A] as we would want).

Copy this code and paste it in your HTML
`/// <summary>/// Convert the argument string into its binary-coded decimal (BCD) representation, e.g.///  "0110" -> { 0x01, 0x10 } (for Big Endian byte order)///  "0110" -> { 0x10, 0x01 } (for Little Endian byte order)///  (NOTE: It is assumed that the string is always a big-endian representation.)/// </summary>/// <param name="isLittleEndian">True if the byte order is "little end first (leftmost)".</param>/// <param name="bcdString">String representation of BCD bytes.</param>/// <returns>Byte array representation of the string as BCD.</returns>/// <exception cref="ArgumentException">Thrown if the argument string isn't entirely made up of BCD pairs.</exception>public static byte[] ConvertToBinaryCodedDecimal(bool isLittleEndian, string bcdString){    bool isValid = true;    isValid = isValid && !String.IsNullOrEmpty(bcdString);    // Check that the string is made up of sets of two numbers (e.g. "01" or "3456")    isValid = isValid && Regex.IsMatch(bcdString, "^([0-9]{2})+\$");    byte[] bytes;    if (isValid)    {        char[] chars = bcdString.ToCharArray();        int len = chars.Length / 2;        bytes = new byte[len];        if (isLittleEndian)        {            for (int i = 0; i < len; i++)            {                byte highNibble = byte.Parse(chars[2 * (len - 1) - 2 * i].ToString());                byte lowNibble = byte.Parse(chars[2 * (len - 1) - 2 * i + 1].ToString());                bytes[i] = (byte)((byte)(highNibble << 4) | lowNibble);            }        }        else        {            for (int i = 0; i < len; i++)            {                byte highNibble = byte.Parse(chars[2 * i].ToString());                byte lowNibble = byte.Parse(chars[2 * i + 1].ToString());                bytes[i] = (byte)((byte)(highNibble << 4) | lowNibble);            }        }    }    else    {        throw new ArgumentException(String.Format(            "Input string ({0}) was invalid.", bcdString));    }    return bytes;}`