日期:2014-05-18 浏览次数:20905 次
class BCD { public enum BcdType { 码8421, 码5421, 码2421, 余3码, 余3循环码 } /// <summary> /// 或BCD表数据 /// </summary> /// <returns></returns> private static DataTable GetBcdTable() { DataTable _BCDTable = new DataTable(); _BCDTable.Columns.Add("十进制数"); _BCDTable.Columns.Add("码8421"); _BCDTable.Columns.Add("码5421"); _BCDTable.Columns.Add("码2421"); _BCDTable.Columns.Add("余3码"); _BCDTable.Columns.Add("余3循环码"); _BCDTable.Rows.Add(new object[] { "0", "0000", "0000", "0000", "0011", "0010" }); _BCDTable.Rows.Add(new object[] { "1", "0001", "0001", "0001", "0100", "0110" }); _BCDTable.Rows.Add(new object[] { "2", "0010", "0010", "0010", "0101", "0111" }); _BCDTable.Rows.Add(new object[] { "3", "0011", "0011", "0011", "0110", "0101" }); _BCDTable.Rows.Add(new object[] { "4", "0100", "0100", "0100", "0111", "0100" }); _BCDTable.Rows.Add(new object[] { "5", "0101", "1000", "1011", "1000", "1100" }); _BCDTable.Rows.Add(new object[] { "6", "0110", "1001", "1100", "1001", "1101" }); _BCDTable.Rows.Add(new object[] { "7", "0111", "1010", "1101", "1010", "1111" }); _BCDTable.Rows.Add(new object[] { "8", "1000", "1011", "1110", "1011", "1110" }); _BCDTable.Rows.Add(new object[] { "9", "1001", "1100", "1111", "1100", "1010" }); return _BCDTable; } /// <summary> /// BCD解码 /// </summary> /// <param name="p_Value">BCD码</param> /// <param name="p_BcdType">BCD码类型</param> /// <param name="p_LongValue">返回数据</param> /// <returns>false 解码失败 true解编成功</returns> public static ulong GetBcdDecode(string p_Value, BcdType p_BcdType) { DataTable _BCDTable = GetBcdTable(); ulong p_LongValue = 0; StringBuilder _Return = new StringBuilder(); if (p_Value.Length % 4 == 0) { int _Count = p_Value.Length / 4; string _ValueText = p_Value.ToString(); for (int i = 0; i != _Count; i++) { DataRow[] _Row = _BCDTable.Select(p_BcdType.ToString() + "=" + _ValueText.Substring(i * 4, 4)); if (_Row.Length == 0) return 0; _Return.Append(_Row[0]["十进制数"].ToString()); } p_LongValue = Convert.ToUInt64(_Return.ToString()); return p_LongValue; } return 0; } /// <summary> /// BCD