Java String to Byte Array convertStringToByteArray(String string)

Here you can find the source of convertStringToByteArray(String string)

Description

convert String To Byte Array

License

Apache License

Parameter

Parameter Description
string is the string which is to be converted.

Return

An array of byte is returned containing the string as bytes.

Declaration

public static byte[] convertStringToByteArray(String string) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//w  w w .j a v  a 2 s  .c  om
     * 
     * @param string
     *            is the string which is to be converted.
     * @return An array of byte is returned containing the string as bytes.
     */
    public static byte[] convertStringToByteArray(String string) {
        if (string == null) {
            throw new IllegalArgumentException("String argument must not be null!");
        }
        if (string.length() % 2 != 0) {
            throw new IllegalArgumentException("String argument has to have a length which can be divided by 2!");
        }
        byte[] bytes = new byte[string.length() / 2];
        StringBuffer buffer = new StringBuffer(string);
        for (int i = 0; i < bytes.length; i++) {
            String hexByteString = buffer.substring(0, 2);
            bytes[i] = Integer.valueOf(hexByteString, 16).byteValue();
            buffer.delete(0, 2);
        }
        return bytes;
    }
}

Related

  1. asBytes(String hex)
  2. asBytes(String hexStr)
  3. convertStringToByte(String input)
  4. convertStringToByte(String strValue)
  5. convertStringToByteArray(String input)
  6. convertStringToBytes(String string)
  7. getBytes(String k)
  8. getBytes(String k)
  9. getBytes(String outputFile, Map queries)