Java Byte Array to String bytesToString(byte[] myByte)

Here you can find the source of bytesToString(byte[] myByte)

Description

Converts array of bytes into string on per-symbol basis, till first 0 value.

License

Creative Commons License

Parameter

Parameter Description
myByte byte array to convert

Return

converted string

Declaration

public static String bytesToString(byte[] myByte) 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

public class Main {
    /**//from   w  ww . ja v  a 2  s  .  c  o m
     * Converts array of bytes into string on per-symbol basis, till first 0 value.
     * 
     * @param myByte byte array to convert
     * @return converted string
     */
    public static String bytesToString(byte[] myByte) {
        return bytesToString(myByte, 0, myByte.length);
    }

    /**
     * Converts array of bytes into string on per-symbol basis, till first 0 value.
     * 
     * @param myByte byte array to convert
     * @param offset number of first byte to convert
     * @param length length of converting part
     * @return converted string
     */
    public static String bytesToString(byte[] myByte, int offset, int length) {
        int trunc = -1;
        for (int i = offset; i < offset + length; i++) {
            if (myByte[i] == 0) {
                trunc = i;
                break;
            }
        }
        if (trunc != -1) {
            // return new String(b, o, trunc - o);
            return quickBytesToString(myByte, offset, trunc - offset);
        } else {
            // return new String(b, o, l);
            return quickBytesToString(myByte, offset, length);
        }
    }

    /**
     * Converts array of bytes into string on per-symbol basis.
     * 
     * @param myByte byte array to convert 
     * @param offset offset from first array member to start conversion
     * @param length resulting string length
     * @return converted string
     */
    public static String quickBytesToString(byte[] myByte, int offset, int length) {
        char[] chars = new char[length];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) myByte[i + offset];
        }
        return new String(chars);
    }
}

Related

  1. bytesToString(byte[] data)
  2. bytesToString(byte[] data, int start, int end)
  3. bytesToString(byte[] hasher)
  4. bytesToString(byte[] id)
  5. bytesToString(byte[] input)
  6. bytesToString(byte[] value)
  7. bytesToString(char[] bytes, boolean le, boolean signed)
  8. bytesToString(final byte[] arr, final boolean signed, final boolean littleEndian, final String sep)
  9. bytesToString(final byte[] bytes)