Convert byte array to String - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert byte array to String

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int bytesPerChar = 42;
        System.out.println(getString(bytes, bytesPerChar));
    }// w  w w  .j  a  v a  2s.c om

    public static String getString(byte[] bytes, int bytesPerChar) {
        char[] chars = new char[bytes.length / bytesPerChar];
        for (int i = 0; i < chars.length; i++) {
            for (int j = 0; j < bytesPerChar; j++) {
                int shift = (bytesPerChar - 1 - j) * 8;
                chars[i] |= (0x000000FF << shift)
                        & (((int) bytes[i * bytesPerChar + j]) << shift);
            }
        }
        return new String(chars);
    }
}

Related Tutorials