集册 Java实例教程 将格式为“[01]*”的字符串转换为位并将其打包为字节数组

将格式为“[01]*”的字符串转换为位并将其打包为字节数组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

553
将格式为“[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) {
展开阅读全文