Java二进制字符串和字节数组转换函数三个

发现Java中没有有直接对纯 '0’和’1’组成的字符串转字节数组的函数,于是自己写了以下三个函数。

byte[] string2bytes(String s)

二制度字符串转字节数组,如 101000000100100101110000 -> A0 09 70

String bytes2String(byte[] bts)

字节数组转字符串,如 A0 09 70 -> 101000000000100101110000

String format(String input)

追加0或1在字长串末尾,使其长度为8的倍数,如 10101 -> 10101000

源代码

public class BinaryFunction{
	public static void main(String[] args) throws IOException {
		String input = "101000000000100101110";
		input = format(input);
		byte[] bts = string2bytes(input);
		for(byte b: bts)
			System.out.printf("%x ", b);
		String output = bytes2String(bts);
		
		System.out.printf("\nInput:  %s\nOutput: %s\nInput == Output: %b\n", input, output, input.equals(output));
	}
	
	/**
	 * 将01字符串的长度增长为8的倍数,不足部分在末尾追回‘0’。
	 * @param input
	 * @return
	 */
	static String format(String input) {
		int remainder = input.length() % 8;  
		StringBuilder sb = new StringBuilder(input);
		if (remainder > 0)
			for (int i = 0; i < 8 - remainder; i++)
				sb.append("0"); 
		return sb.toString();
	}

	/**
	 * 二制度字符串转字节数组,如 101000000100100101110000 -> A0 09 70
	 * @param input 输入字符串。
	 * @return 转换好的字节数组。
	 */
	static byte[] string2bytes(String input) { 
		StringBuilder in = new StringBuilder(input); 
		// 注:这里in.length() 不可在for循环内调用,因为长度在变化 
		int remainder = in.length() % 8; 
		if (remainder > 0)
			for (int i = 0; i < 8 - remainder; i++)
				in.append("0"); 
		byte[] bts = new byte[in.length() / 8];

		// Step 8 Apply compression
		for (int i = 0; i < bts.length; i++)
			bts[i] = (byte) Integer.parseInt(in.substring(i * 8, i * 8 + 8), 2);

		return bts; 
	}
	
	/**
	 * 字节数组转字符串,如 A0 09 70 -> 101000000000100101110000。
	 * @param bts 转入字节数组。
	 * @return 转换好的只有“1”和“0”的字符串。
	 */
	static String bytes2String(byte[] bts) {
		String[] dic = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", 
				"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
		StringBuilder out = new StringBuilder();
		for (byte b : bts) {
			String s = String.format("%x", b);
			s = s.length() == 1? "0" + s: s;
			out.append(dic[Integer.parseInt(s.substring(0, 1), 16)]);
			out.append(dic[Integer.parseInt(s.substring(1, 2), 16)]);
		}
		return out.toString();
	}
}	

猜你喜欢

转载自blog.csdn.net/weixin_43145361/article/details/89765906