51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

压缩型BCD编码(java)

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<b.length;i++) {
		b[i] = (<span class="hljs-type">byte</span>) (s[<span class="hljs-number">2</span>*i] << <span class="hljs-number">4</span> | (s[<span class="hljs-number">2</span>*i+<span class="hljs-number">1</span>] & <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<bcd.length;i++) {
		sb.append(bcd[i]>><span class="hljs-number">4</span>&<span class="hljs-number">0xf</span>)
		.append(bcd[i]&<span class="hljs-number">0xf</span>);
	}
	<span class="hljs-keyword">return</span> sb.toString();
}

}


赞(1)
未经允许不得转载:工具盒子 » 压缩型BCD编码(java)