Convert a binary coded decimal (BCD) string into bytes


/ Published in: C#
Save to your folder(s)

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
  1. /// <summary>
  2. /// Convert the argument string into its binary-coded decimal (BCD) representation, e.g.
  3. /// "0110" -> { 0x01, 0x10 } (for Big Endian byte order)
  4. /// "0110" -> { 0x10, 0x01 } (for Little Endian byte order)
  5. /// (NOTE: It is assumed that the string is always a big-endian representation.)
  6. /// </summary>
  7. /// <param name="isLittleEndian">True if the byte order is "little end first (leftmost)".</param>
  8. /// <param name="bcdString">String representation of BCD bytes.</param>
  9. /// <returns>Byte array representation of the string as BCD.</returns>
  10. /// <exception cref="ArgumentException">Thrown if the argument string isn't entirely made up of BCD pairs.</exception>
  11. public static byte[] ConvertToBinaryCodedDecimal(bool isLittleEndian, string bcdString)
  12. {
  13. bool isValid = true;
  14. isValid = isValid && !String.IsNullOrEmpty(bcdString);
  15. // Check that the string is made up of sets of two numbers (e.g. "01" or "3456")
  16. isValid = isValid && Regex.IsMatch(bcdString, "^([0-9]{2})+$");
  17. byte[] bytes;
  18. if (isValid)
  19. {
  20. char[] chars = bcdString.ToCharArray();
  21. int len = chars.Length / 2;
  22. bytes = new byte[len];
  23. if (isLittleEndian)
  24. {
  25. for (int i = 0; i < len; i++)
  26. {
  27. byte highNibble = byte.Parse(chars[2 * (len - 1) - 2 * i].ToString());
  28. byte lowNibble = byte.Parse(chars[2 * (len - 1) - 2 * i + 1].ToString());
  29. bytes[i] = (byte)((byte)(highNibble << 4) | lowNibble);
  30. }
  31. }
  32. else
  33. {
  34. for (int i = 0; i < len; i++)
  35. {
  36. byte highNibble = byte.Parse(chars[2 * i].ToString());
  37. byte lowNibble = byte.Parse(chars[2 * i + 1].ToString());
  38. bytes[i] = (byte)((byte)(highNibble << 4) | lowNibble);
  39. }
  40. }
  41. }
  42. else
  43. {
  44. throw new ArgumentException(String.Format(
  45. "Input string ({0}) was invalid.", bcdString));
  46. }
  47. return bytes;
  48. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.