关键词搜索

源码搜索 ×
×

Java & C# BCD编码与十进制转换

发布2018-10-30浏览2099次

详情内容

目录

BCD码介绍

 Java版本互转工具

C#版本互转工具


BCD码介绍

  • BCD码(Binary-Coded Decimal‎)亦称二进码十进数或二-十进制代码。用4位二进制数来表示1位十进制数中的0~9这10个数码。是一种二进制的数字编码形式,用二进制编码的十进制代码。BCD码这种编码形式利用了四个位元来储存一个十进制的数码,使二进制和十进制之间的转换得以快捷的进行。这种编码技巧最常用于会计系统的设计里,因为会计制度经常需要对很长的数字串作准确的计算。相对于一般的浮点式记数法,采用BCD码,既可保存数值的精确度,又可免却使电脑作浮点运算时所耗费的时间。此外,对于其他需要高精确度的计算,BCD编码亦很常用。
  • BCD码是四位二进制码, 也就是将十进制的数字转化为二进制, 但是和普通的转化有一点不同, 每一个十进制的数字0-9都对应着一个四位的二进制码,对应关系如下: 十进制0 对应 二进制0000 ;十进制1 对应二进制0001 ....... 9 1001 接下来的10就有两个上述的码来表示 10 表示为00010000 也就是BCD码是遇见1001就产生进位,不象普通的二进制码,到1111才产生进位10000
  • 在Java通信应用中,往往我们接收到数据流,而流是BCD编码后的。因此我们要转码来获得我们想要的十进制数据。下面的代码是BCD编码的数据流与十进制的转换,仅供参考。

常用BCD码

十进制数8421码5421码2421码余3码余3循环码
000000000000000110010
100010001000101000110
200100010001001010111
300110011001101100101
401000100010001110100
501011000101110001100
601101001110010011101
701111010110110101111
810001011111010111110
910011100111111001010

 Java版本互转工具

  1. package com.util;
  2. /**
  3. * 编码工具类
  4. *
  5. * @author 崔素强
  6. * @see BCD与十进制的转换
  7. */
  8. public class BCDDecode {
  9. /**
  10. * @功能:测试用例
  11. * @参数: 参数
  12. */
  13. public static void main(String[] args) {
  14. byte[] b = str2Bcd("https://files.jxasp.com/image/2010");
  15. System.out.println(bcd2Str(b));
  16. }
  17. /**
  18. * @功能: BCD码转为10进制串(阿拉伯数据)
  19. * @参数: BCD码
  20. * @结果: 10进制串
  21. */
  22. public static String bcd2Str(byte[] bytes) {
  23. StringBuffer temp = new StringBuffer(bytes.length * 2);
  24. for (int i = 0; i < bytes.length; i++) {
  25. temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
  26. temp.append((byte) (bytes[i] & 0x0f));
  27. }
  28. return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp
  29. .toString().substring(1) : temp.toString();
  30. }
  31. /**
  32. * @功能: 10进制串转为BCD码
  33. * @参数: 10进制串
  34. * @结果: BCD码
  35. */
  36. public static byte[] str2Bcd(String asc) {
  37. int len = asc.length();
  38. int mod = len % 2;
  39. if (mod != 0) {
  40. asc = "0" + asc;
  41. len = asc.length();
  42. }
  43. byte abt[] = new byte[len];
  44. if (len >= 2) {
  45. len = len / 2;
  46. }
  47. byte bbt[] = new byte[len];
  48. abt = asc.getBytes();
  49. int j, k;
  50. for (int p = 0; p < asc.length() / 2; p++) {
  51. if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
  52. j = abt[2 * p] - '0';
  53. } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
  54. j = abt[2 * p] - 'a' + 0x0a;
  55. } else {
  56. j = abt[2 * p] - 'A' + 0x0a;
  57. }
  58. if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
  59. k = abt[2 * p + 1] - '0';
  60. } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
  61. k = abt[2 * p + 1] - 'a' + 0x0a;
  62. } else {
  63. k = abt[2 * p + 1] - 'A' + 0x0a;
  64. }
  65. int a = (j << 4) + k;
  66. byte b = (byte) a;
  67. bbt[p] = b;
  68. }
  69. return bbt;
  70. }
  71. }

C#版本互转工具

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Base
  5. {
  6. public class BCDHelper
  7. {
  8. /// <summary>
  9. /// 用BCD码压缩数字字符串
  10. /// </summary>
  11. /// <param name="str"></param>
  12. /// <returns></returns>
  13. public static byte[] StrToBCD(string str)
  14. {
  15. return StrToBCD(str, str.Length);
  16. }
  17. public static byte[] StrToBCD(string str, int numlen)
  18. {
  19. while (str.Length < numlen)
  20. {
  21. str = "0" + str;
  22. }
  23. return ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes(str), 0, numlen);
  24. }
  25. /// <summary>
  26. /// 用BCD码压缩数字字符串
  27. /// </summary>
  28. /// <param name="NumBitByte"></param>
  29. /// <param name="offset">偏移量</param>
  30. /// <param name="numlen">数字字符串位数</param>
  31. /// <returns></returns>
  32. /// <remarks></remarks>
  33. public static byte[] ByteArrayToBCD(byte[] NumBitByte, int offset, int numlen)
  34. {
  35. //8位的ascii码
  36. int Num4Len = (numlen + 1) / 2 - 1;
  37. byte[] Num4bitByte = new byte[Num4Len + 1];
  38. Num4bitByte[Num4Len] = 0;
  39. for (int i = 0; i <= numlen - 1; i++)
  40. {
  41. byte num = 0;
  42. if (i + offset >= NumBitByte.Length)
  43. {
  44. //num = 255;
  45. num = 0;
  46. }
  47. else
  48. {
  49. num = Convert.ToByte(NumBitByte[i + offset] - 0x30);
  50. }
  51. if (i % 2 == 0)
  52. {
  53. Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] & 0xf) | ((num << 4) & 0xFF));
  54. }
  55. else
  56. {
  57. Num4bitByte[i / 2] = Convert.ToByte((Num4bitByte[i / 2] & 0xf0) | num);
  58. }
  59. }
  60. return Num4bitByte;
  61. }
  62. /// <summary>
  63. /// BCD转int
  64. /// </summary>
  65. /// <param name="bcdNum"></param>
  66. /// <param name="offset">偏移量</param>
  67. /// <param name="numlen">数字字符串位数</param>
  68. /// <returns></returns>
  69. /// <remarks></remarks>
  70. public static int bcdToInt(byte[] bcdNum, int offset, int numlen)
  71. {
  72. return Convert.ToInt32(bcdToString(bcdNum, offset, numlen));
  73. }
  74. /// <summary>
  75. /// BCD转字符串
  76. /// </summary>
  77. /// <param name="bcdNum"></param>
  78. /// <param name="offset">偏移量</param>
  79. /// <param name="numlen">数字字符串位数</param>
  80. /// <returns></returns>
  81. /// <remarks></remarks>
  82. public static string bcdToString(byte[] bcdNum, int offset, int numlen)
  83. {
  84. string retString = "";
  85. int res;
  86. var len = Math.DivRem(numlen, 2, out res);
  87. if (res != 0)
  88. {
  89. len++;
  90. }
  91. for (int i = 0; i < len; i++)
  92. {
  93. retString += ((bcdNum[i + offset] & 0xf0) >> 4).ToString("x");
  94. retString += (bcdNum[i + offset] & 0xf).ToString("x");
  95. }
  96. //Dim byteChar As Byte() = New Byte(length - 1) {}
  97. //Dim tempHigh As Byte = 0, tempLow As Byte = 0
  98. //Dim i As Integer = 0
  99. //While tempHigh <> &HF AndAlso tempLow <> &HF0
  100. // tempHigh = Convert.ToByte(bcdNum(i + offset) And &HF0)
  101. // '取出高四位;
  102. // tempHigh = Convert.ToByte(tempHigh >> 4)
  103. // tempLow = Convert.ToByte((bcdNum(i + offset) And &HF) << 4)
  104. // byteChar(i) = Convert.ToByte(tempLow Or tempHigh)
  105. // i += 1
  106. //End While
  107. //Dim HexString As String() = BitConverter.ToString(byteChar).Trim().Split("-"c)
  108. //For Each str As String In HexString
  109. // retString += str.Trim()
  110. //Next
  111. //Dim LastIndex As Integer = retString.IndexOf("F"c)
  112. //retString = retString.Substring(0, LastIndex)
  113. return retString.ToLower().Replace("f", "");
  114. }
  115. /// <summary>
  116. /// BCD码转小时分钟
  117. /// date:2012-12-18
  118. /// author:guozh
  119. /// </summary>
  120. /// <param name="data"></param>
  121. /// <param name="offset">偏移位</param>
  122. /// <returns></returns>
  123. /// <remarks></remarks>
  124. public static System.DateTime Bcd2ToDateTime(byte[] data, int offset)
  125. {
  126. Int32 hour = default(Int32);
  127. Int32 minute = default(Int32);
  128. hour = Convert.ToInt32(bcdToString(data, offset, 2));
  129. minute = Convert.ToInt32(bcdToString(data, offset + 1, 2));
  130. return new System.DateTime(0000, 00, 00, hour, minute, 00);
  131. }
  132. /// <summary>
  133. /// BCD码转日期
  134. /// </summary>
  135. /// <param name="data"></param>
  136. /// <param name="offset">偏移位</param>
  137. /// <returns></returns>
  138. /// <remarks></remarks>
  139. public static System.DateTime Bcd3ToDateTime(byte[] data, int offset)
  140. {
  141. Int32 year = default(Int32);
  142. Int32 month = default(Int32);
  143. Int32 day = default(Int32);
  144. year = Convert.ToInt32("https://files.jxasp.com/image/20" + bcdToString(data, offset, 2));
  145. month = Convert.ToInt32(bcdToString(data, offset + 1, 2));
  146. day = Convert.ToInt32(bcdToString(data, offset + 2, 2));
  147. if (day == 0 || month == 0)
  148. {
  149. return DateTime.MinValue;
  150. }
  151. return new System.DateTime(year, month, day);
  152. }
  153. public static System.DateTime Bcd4ToDateTime(byte[] data, int offset)
  154. {
  155. Int32 year = default(Int32);
  156. Int32 month = default(Int32);
  157. Int32 day = default(Int32);
  158. try
  159. {
  160. year = Convert.ToInt32(bcdToString(data, offset, 4));
  161. month = Convert.ToInt32(bcdToString(data, offset + 2, 2));
  162. day = Convert.ToInt32(bcdToString(data, offset + 3, 2));
  163. }
  164. catch
  165. {
  166. }
  167. if (day == 0 || month == 0)
  168. {
  169. return DateTime.MinValue;
  170. }
  171. return new System.DateTime(year, month, day);
  172. }
  173. public static System.DateTime Bcd5ToDateTime(byte[] data, int offset)
  174. {
  175. var year = Convert.ToInt32("https://files.jxasp.com/image/20" + bcdToString(data, offset, 2));
  176. var month = Convert.ToInt32(bcdToString(data, offset + 1, 2));
  177. var day = Convert.ToInt32(bcdToString(data, offset + 2, 2));
  178. var hour = Convert.ToInt32(bcdToString(data, offset + 3, 2));
  179. var minute = Convert.ToInt32(bcdToString(data, offset + 4, 2));
  180. if (day == 0 || month == 0)
  181. {
  182. return DateTime.MinValue;
  183. }
  184. return new DateTime(year, month, day, hour, minute, 0);
  185. }
  186. /// <summary>
  187. /// BCD码转时间格式
  188. /// </summary>
  189. /// <param name="data"></param>
  190. /// <param name="offset">偏移位</param>
  191. /// <returns></returns>
  192. /// <remarks></remarks>
  193. public static System.DateTime Bcd6ToDateTime(byte[] data, int offset)
  194. {
  195. try
  196. {
  197. if (data.Length < offset + 6)
  198. {
  199. return DateTime.MinValue;
  200. }
  201. int year;// = Convert.ToInt32("https://files.jxasp.com/image/20" + bcdToString(data, offset, 2));
  202. if (!int.TryParse("https://files.jxasp.com/image/20" + bcdToString(data, offset, 2), out year))
  203. {
  204. return DateTime.MinValue;
  205. }
  206. int month;// = Convert.ToInt32(bcdToString(data, offset + 1, 2));
  207. if (!int.TryParse(bcdToString(data, offset + 1, 2), out month))
  208. {
  209. return DateTime.MinValue;
  210. }
  211. int day;// = Convert.ToInt32(bcdToString(data, offset + 2, 2));
  212. if (!int.TryParse(bcdToString(data, offset + 2, 2), out day))
  213. {
  214. return DateTime.MinValue;
  215. }
  216. int hour;// = Convert.ToInt32(bcdToString(data, offset + 3, 2));
  217. if (!int.TryParse(bcdToString(data, offset + 3, 2), out hour))
  218. {
  219. return DateTime.MinValue;
  220. }
  221. int minute;// = Convert.ToInt32(bcdToString(data, offset + 4, 2));
  222. if (!int.TryParse(bcdToString(data, offset + 4, 2), out minute))
  223. {
  224. return DateTime.MinValue;
  225. }
  226. int second;// = Convert.ToInt32(bcdToString(data, offset + 5, 2));
  227. if (!int.TryParse(bcdToString(data, offset + 5, 2), out second))
  228. {
  229. return DateTime.MinValue;
  230. }
  231. if (day == 0 || month == 0 || month > 12 || day > 31 || hour > 24 || minute > 60 || second > 60)
  232. {
  233. return DateTime.MinValue;
  234. }
  235. return new DateTime(year, month, day, hour, minute, second);
  236. }
  237. catch
  238. {
  239. return DateTime.MinValue;
  240. }
  241. }
  242. /// <summary>
  243. ///
  244. /// </summary>
  245. /// <param name="data"></param>
  246. /// <param name="offset"></param>
  247. /// <returns></returns>
  248. public static System.DateTime Bcd7ToDateTime(byte[] data, int offset)
  249. {
  250. var year = Convert.ToInt32(bcdToString(data, offset, 4));
  251. var month = Convert.ToInt32(bcdToString(data, offset + 2, 2));
  252. var day = Convert.ToInt32(bcdToString(data, offset + 3, 2));
  253. var hour = Convert.ToInt32(bcdToString(data, offset + 4, 2));
  254. var minute = Convert.ToInt32(bcdToString(data, offset + 5, 2));
  255. var second = Convert.ToInt32(bcdToString(data, offset + 6, 2));
  256. if (day == 0 || month == 0 || year == 0)
  257. {
  258. return DateTime.MinValue;
  259. }
  260. return new DateTime(year, month, day, hour, minute, second);
  261. }
  262. /// <summary>
  263. /// 小时分钟转BCD码
  264. /// date:2012-12-18
  265. /// author:guozh
  266. /// </summary>
  267. /// <param name="dt"></param>
  268. /// <returns></returns>
  269. /// <remarks></remarks>
  270. public static byte[] DateTimeToBcd2(System.DateTime dt)
  271. {
  272. List<byte> lst = new List<byte>();
  273. //StringBuilder sb = new StringBuilder();
  274. //sb.Append(dt.Hour.ToString("D2"));
  275. //sb.Append(dt.Minute.ToString("D2"));
  276. lst.AddRange(StrToBCD(dt.ToString("HHmm")));
  277. return lst.ToArray();
  278. }
  279. /// <summary>
  280. /// 日期转BCD码
  281. /// </summary>
  282. /// <param name="dt"></param>
  283. /// <returns></returns>
  284. /// <remarks></remarks>
  285. public static byte[] DateTimeToBcd3(System.DateTime dt)
  286. {
  287. List<byte> lst = new List<byte>();
  288. //StringBuilder sb = new StringBuilder();
  289. //sb.Append((dt.Year - 2000).ToString("D2"));
  290. //sb.Append(dt.Month.ToString("D2"));
  291. //sb.Append(dt.Day.ToString("D2"));
  292. lst.AddRange(StrToBCD(dt.ToString("yyMMdd")));
  293. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Year - 2000).ToString()), 0, 2));
  294. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Month).ToString()), 0, 2));
  295. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Day).ToString()), 0, 2));
  296. return lst.ToArray();
  297. }
  298. public static byte[] DateTimeToBcd4(System.DateTime dt)
  299. {
  300. List<byte> lst = new List<byte>();
  301. StringBuilder sb = new StringBuilder();
  302. sb.Append((dt.Year).ToString("D4"));
  303. sb.Append(dt.Month.ToString("D2"));
  304. sb.Append(dt.Day.ToString("D2"));
  305. lst.AddRange(StrToBCD(sb.ToString()));
  306. return lst.ToArray();
  307. }
  308. public static byte[] DateTimeToBcd5(System.DateTime dt)
  309. {
  310. List<byte> lst = new List<byte>();
  311. var strTime = dt.ToString("yyMMddHHmm");
  312. lst.AddRange(StrToBCD(strTime));
  313. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Year - 2000).ToString()), 0, 2));
  314. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Month).ToString()), 0, 2));
  315. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Day).ToString()), 0, 2));
  316. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Hour).ToString()), 0, 2));
  317. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Minute).ToString()), 0, 2));
  318. return lst.ToArray();
  319. }
  320. public static byte[] DateTimeToBcd6(System.DateTime dt)
  321. {
  322. try
  323. {
  324. List<byte> lst = new List<byte>();
  325. var strTime = dt.ToString("yyMMddHHmmss");
  326. lst.AddRange(StrToBCD(strTime));
  327. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Year - 2000).ToString()), 0, 2));
  328. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Month).ToString()), 0, 2));
  329. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Day).ToString()), 0, 2));
  330. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Hour).ToString()), 0, 2));
  331. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Minute).ToString()), 0, 2));
  332. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Second).ToString()), 0, 2));
  333. return lst.ToArray();
  334. }
  335. catch (System.Exception ex)
  336. {
  337. return new byte[] { 0, 0, 0, 0, 0, 0 };
  338. }
  339. }
  340. public static byte[] DateTimeToBcd7(System.DateTime dt)
  341. {
  342. List<byte> lst = new List<byte>();
  343. StringBuilder sb = new StringBuilder();
  344. sb.Append(dt.Year.ToString("D4"));
  345. sb.Append(dt.Month.ToString("D2"));
  346. sb.Append(dt.Day.ToString("D2"));
  347. sb.Append(dt.Hour.ToString("D2"));
  348. sb.Append(dt.Minute.ToString("D2"));
  349. sb.Append(dt.Second.ToString("D2"));
  350. lst.AddRange(StrToBCD(sb.ToString()));
  351. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes(dt.Year.ToString()), 0, 4));
  352. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Month).ToString()), 0, 2));
  353. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Day).ToString()), 0, 2));
  354. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Hour).ToString()), 0, 2));
  355. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Minute).ToString()), 0, 2));
  356. //lst.AddRange(ByteArrayToBCD(System.Text.Encoding.ASCII.GetBytes((dt.Second).ToString()), 0, 2));
  357. return lst.ToArray();
  358. }
  359. }
  360. }

参考文章:http://cuisuqiang.iteye.com/blog/1429956 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载