将格式为“[01]*”的字符串转换为位并将其打包为字节数组
//package com.nowjava; import java.io.ByteArrayOutputStream; /* nowjava.com - 时 代 Java */ public class Main { /** * Converts a string in the form "[01]*" into bits and packs them into byte * array * * @param str * @return */ public static byte[] binaryStringToBytes(String str) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int curByte = 0; int i, bc = 0; for (i = 0; i < str.length(); i++) { int bit; char charAt = str.charAt(i); if (charAt == '1') bit = 1; else if (charAt == '0') bit = 0; else /* N o w J a v a . c o m 提供 */ continue; curByte |= bit << (7 - bc % 8); if (bc % 8 == 7) {