# Posted By

pckujawa on 07/09/09

# Statistics

Viewed 1377 times
Favorited by 1 user(s)

# Convert bytes into a binary coded decimal (BCD) string

/ 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.

There is actually a built-in method to do BCD: System.BitConverter.ToString. Note, though, that BitConverter only uses the endianness of the host machine, so you might need to convert to Big or Little Endian depending on the data source or destination.

Example: `BitConverter.ToString(new byte[] {0xAE, 0xD0})` gives us the string `AE-D0`.

Copy this code and paste it in your HTML
`/// <summary>/// Convert the argument bytes into their binary-coded decimal (BCD) representation, e.g./// { 0x01, 0x10 } -> "0110" (for Big Endian byte order)/// { 0x01, 0x10 } -> "1001" (for Little Endian byte order)/// </summary>/// <param name="isLittleEndian">True if the byte order is "little end first (leftmost)".</param>/// <param name="bytes">A comma-separated list of bytes or byte array</param>/// <returns>String representation of the bytes as BCD.</returns>/// <exception cref="ArgumentException">Thrown if the argument bytes contain non-BCD data (e.g. nibble values with 0xA-0xF).</exception>public static string ConvertToBinaryCodedDecimal(bool isLittleEndian, params byte[] bytes){    StringBuilder bcd = new StringBuilder(bytes.Length * 2);    if (isLittleEndian)    {        for (int i = bytes.Length-1; i >= 0; i--)        {            byte bcdByte = bytes[i];            int idHigh = bcdByte >> 4;            int idLow = bcdByte & 0x0F;            if (idHigh > 9 || idLow > 9)            {                throw new ArgumentException(                    String.Format("One of the argument bytes was not in binary-coded decimal format: byte[{0}] = 0x{1:X2}.",                    i, bcdByte));            }            bcd.Append(string.Format("{0}{1}", idHigh, idLow));        }    }    else    {        for (int i = 0; i < bytes.Length; i++)        {            byte bcdByte = bytes[i];            int idHigh = bcdByte >> 4;            int idLow = bcdByte & 0x0F;            if (idHigh > 9 || idLow > 9)            {                throw new ArgumentException(                    String.Format("One of the argument bytes was not in binary-coded decimal format: byte[{0}] = 0x{1:X2}.",                    i, bcdByte));            }            bcd.Append(string.Format("{0}{1}", idHigh, idLow));        }    }    return bcd.ToString();}` Subscribe to comments