Java Byte Array Create toByteString(final String source)

Here you can find the source of toByteString(final String source)

Description

to Byte String

License

Apache License

Declaration

public static String toByteString(final String source) 

Method Source Code

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

public class Main {

    public static String toByteString(final String source) {
        if (source == null) {
            return null;
        }// www .ja  va 2  s  .  c o m

        if (source.length() == 0) {
            return "";
        }

        final char[] chars = source.toCharArray();
        final byte[] bytes = new byte[source.length() * 2];
        int index = 0;

        for (int i = 0, charValue = 0; (i < chars.length)
                && (index < (chars.length * 2)); i++) {
            charValue = chars[i];

            if (charValue > 255) {
                try {
                    final byte[] tmp = (new Character(chars[i])).toString()
                            .getBytes("GB2312");

                    for (int j = 0; j < tmp.length; j++) {
                        bytes[index] = tmp[j];
                        index++;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            } else {
                bytes[index] = (byte) chars[i];
                index++;
            }
        }

        return new String(bytes, 0, index);
    }

    /**
     * To string.
     *
     * @param obj the obj
     * @return the string
     */
    public static String toString(final Object obj) {
        if (obj == null) {
            return "";
        } else {
            return obj.toString();
        }
    }
}

Related

  1. toBytesShortBE(short w)
  2. toBytesString(byte[] bytes)
  3. toByteString(byte[] bytes, String seperator)
  4. toByteString(byte[] content, int len)
  5. toByteString(final byte[] b)
  6. toBytesWithLength(byte[] buffer, int pos, String string)
  7. toBytesWithLengthLong(byte[] buffer, int pos, byte[] bytes)