Posted By

pckujawa on 07/09/09

Statistics

Viewed 1763 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
1. /// <summary>
2. /// Convert the argument bytes into their binary-coded decimal (BCD) representation, e.g.
3. /// { 0x01, 0x10 } -> "0110" (for Big Endian byte order)
4. /// { 0x01, 0x10 } -> "1001" (for Little Endian byte order)
5. /// </summary>
6. /// <param name="isLittleEndian">True if the byte order is "little end first (leftmost)".</param>
7. /// <param name="bytes">A comma-separated list of bytes or byte array</param>
8. /// <returns>String representation of the bytes as BCD.</returns>
9. /// <exception cref="ArgumentException">Thrown if the argument bytes contain non-BCD data (e.g. nibble values with 0xA-0xF).</exception>
10. public static string ConvertToBinaryCodedDecimal(bool isLittleEndian, params byte[] bytes)
11. {
12. StringBuilder bcd = new StringBuilder(bytes.Length * 2);
13. if (isLittleEndian)
14. {
15. for (int i = bytes.Length-1; i >= 0; i--)
16. {
17. byte bcdByte = bytes[i];
18. int idHigh = bcdByte >> 4;
19. int idLow = bcdByte & 0x0F;
20. if (idHigh > 9 || idLow > 9)
21. {
22. throw new ArgumentException(
23. String.Format("One of the argument bytes was not in binary-coded decimal format: byte[{0}] = 0x{1:X2}.",
24. i, bcdByte));
25. }
26. bcd.Append(string.Format("{0}{1}", idHigh, idLow));
27. }
28. }
29. else
30. {
31. for (int i = 0; i < bytes.Length; i++)
32. {
33. byte bcdByte = bytes[i];
34. int idHigh = bcdByte >> 4;
35. int idLow = bcdByte & 0x0F;
36. if (idHigh > 9 || idLow > 9)
37. {
38. throw new ArgumentException(
39. String.Format("One of the argument bytes was not in binary-coded decimal format: byte[{0}] = 0x{1:X2}.",
40. i, bcdByte));
41. }
42. bcd.Append(string.Format("{0}{1}", idHigh, idLow));
43. }
44. }
45. return bcd.ToString();
46. } Subscribe to comments