bcd 8421码

bcd码表:

比如一个字符串 String s = "0200"
按对照表转换成二进制
02 : 0000 0010
00 : 0000 0000
s转换为字节的时候
02和00分别转换为一个字节
也就是说字符串"0200"bcd编码之后会是2个字节
代码:

public static byte[] str2bcdOne(String s) {
		//如果不是2的倍数,则补0
		if (s.length() % 2 != 0) {
			s = s + "0";
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//获得字符数组
		char[] cs = s.toCharArray();
		int high = 0;
		int low = 0;
		for (int i = 0; i < cs.length; i += 2) {
			if ((cs[i] >= '0') && (cs[i] <= '9'))
				//得到高位的十进制表示
				high = cs[i] - '0';
			else {
				//溢出
				high = cs[i] - '0' - 7;
			}

			if ((cs[(i + 1)] >= '0') && (cs[(i + 1)] <= '9'))
				//得到低位的十进制表示
				low = cs[(i + 1)] - '0';
			else {
				low = cs[(i + 1)] - '0' - 7;
			}
			System.out.println("high:" +high);
			System.out.println("high2:" +DataConverter.intToBinary(high));
			System.out.println("low:" + DataConverter.intToBinary(low));
			System.out.println("high << 4 | low:" + DataConverter.intToBinary(high << 4 | low));
			baos.write(high << 4 | low);
		}
		return baos.toByteArray();
	}

posted @ 2015-08-13 16:11  风过无痕的博客  阅读(958)  评论(0编辑  收藏  举报