Java Byte Array Create toByteArray(String binString)

Here you can find the source of toByteArray(String binString)

Description

to Byte Array

License

Apache License

Declaration

public static byte[] toByteArray(String binString) 

Method Source Code

//package com.java2s;
/*/*w ww.  j  av  a  2  s  . c om*/
 * Copyright 2014 SunYiJun
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

public class Main {
    public static byte[] toByteArray(String binString) {
        if (binString == null) {
            return null;
        }
        binString = binString.replaceAll(" ", "");
        if (binString.isEmpty()) {
            return new byte[0];
        }
        int length = binString.length();
        int bytesCount = (length + 7) >>> 3;
        int firstByteStringLength = length & 0x07;
        byte[] bytes = new byte[bytesCount];
        if (firstByteStringLength != 0) {
            bytes[0] = (byte) Integer.parseInt(binString.substring(0, firstByteStringLength), 2);
        } else {
            bytes[0] = (byte) Integer.parseInt(binString.substring(0, 8), 2);
            firstByteStringLength = 8;
        }
        int startIndex = firstByteStringLength;
        for (int i = 1; i < bytesCount; i++) {
            bytes[i] = (byte) Integer.parseInt(binString.substring(startIndex, startIndex + 8), 2);
            startIndex += 8;
        }
        return bytes;
    }
}

Related

  1. toByteArray(Number[] array)
  2. toByteArray(Object obj)
  3. toByteArray(Object value)
  4. toByteArray(short foo)
  5. toByteArray(String address)
  6. toByteArray(String bytesStr, int byteLength)
  7. toByteArray(String content, String charsetName)
  8. toByteArray(String hex)
  9. toByteArray(String hex)