Convert string To Bytes - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert string To Bytes

Demo Code


//package com.java2s;

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

    public static byte[] stringToBytes(String value) {
        try {
            int len = value.length() / 3;
            byte[] result = new byte[len];
            for (int i = 0; i < len; i++) {
                result[i] = (byte) (Integer.parseInt(value.substring(i * 3,
                        i * 3 + 3)) - 128);
            }
            return result;
        } catch (NumberFormatException ex) {
            return new byte[0];
        }

    }
}

Related Tutorials