Convert String as Bin byte array - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Convert String as Bin byte array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String src = "java2s.com";
        System.out.println(java.util.Arrays.toString(asBin(src)));
    }//from   ww w .  j  a v  a  2s  .  c o  m

    private static byte[] asBin(String src) {
        if (src.length() < 1)
            return null;
        byte[] encrypted = new byte[src.length() / 2];
        for (int i = 0; i < src.length() / 2; i++) {
            int high = Integer
                    .parseInt(src.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2),
                    16);
            encrypted[i] = (byte) (high * 16 + low);
        }
        return encrypted;
    }
}

Related Tutorials