BCD码,全称 二进制编码的十进制(Binary-Coded Decimal),指的就是用四位二进制数表示一位BCD码,用一个字节表示的两位BCD码,称为压缩型BCD码。
/** * BCD编码 * @author Administrator * */ public class BCD {
<span class="hljs-comment">/** * 将十进制字符串转换为 BCD编码 * <span class="hljs-doctag">@param</span> str * <span class="hljs-doctag">@return</span> */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-type">byte</span>[] String_BCD(String str) { <span class="hljs-type">byte</span>[] s = str.getBytes(); <span class="hljs-type">byte</span>[] b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">byte</span>[s.length/<span class="hljs-number">2</span>]; <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i&lt;b.length;i++) { b[i] = (<span class="hljs-type">byte</span>) (s[<span class="hljs-number">2</span>*i] &lt;&lt; <span class="hljs-number">4</span> | (s[<span class="hljs-number">2</span>*i+<span class="hljs-number">1</span>] &amp; <span class="hljs-number">0xf</span>)); } <span class="hljs-keyword">return</span> b; } <span class="hljs-comment">/** * 将BCD编码的byte数组转换为String * <span class="hljs-doctag">@param</span> bcd * <span class="hljs-doctag">@return</span> */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">BCD_String</span><span class="hljs-params">(<span class="hljs-type">byte</span>[] bcd)</span> { <span class="hljs-type">StringBuilder</span> <span class="hljs-variable">sb</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringBuilder</span>(); <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i&lt;bcd.length;i++) { sb.append(bcd[i]&gt;&gt;<span class="hljs-number">4</span>&amp;<span class="hljs-number">0xf</span>) .append(bcd[i]&amp;<span class="hljs-number">0xf</span>); } <span class="hljs-keyword">return</span> sb.toString(); }
}