Convert String to Byte Array - Java java.lang

Java examples for java.lang:byte Array Convert

Introduction

The following code shows how to convert String to Byte Array.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String binString = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(toByteArray(binString)));
    }/* w w w  .  j a va 2  s  . co  m*/

    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 Tutorials