Byte[] to char[]

30,705

Solution 1

Why you need to stick to strings, use array of char array, first append extra 0 in case its short and If your data is in byte format, use bytes1.toString() and then something like this,

public class Example {

    public static void main(String args[])
    {
        String[] byte1 = {"2","45","56","1"};
        for (int i = 0; i < byte1.length; i++) {
            if(byte1[i].length()<2){
                byte1[i] = "0"+byte1[i];
            }
        }
        char[][] chr = new char[5][10];
        StringBuilder buffer = new StringBuilder();
        for(int i = 0; i < byte1.length;i++){
               chr[i] = byte1[i].toCharArray();
        }


    for (int i = 0; i < chr.length; i++) {
            System.out.println(chr[i]);
    }
    }
}

Solution 2

If you just need a printable representation:

String readable = Arrays.toString(byte1);

But as stated you need a string Array like thing for this.

Share:
30,705
Jeetesh Nataraj
Author by

Jeetesh Nataraj

Updated on January 07, 2020

Comments

  • Jeetesh Nataraj
    Jeetesh Nataraj over 4 years

    I am in a requirement of display raw byte data in char form, there are some issue I am stuck like for example [ 1, 32, -1, -1 ] ( byte data ) which when converted into char comes as [1, 3, 2, -, 1, - ,1]

    My requirement

    [ 1, 32, -1, -1 ] in char format.

    Intailly

    I used the command

    StringBuilder buffer = new StringBuilder();
        for(int i = 0; i < byte1.length;i++){
        buffer.append(byte1[i]);
        }
    char[] c = buffer.toString().toCharArray();
    

    Didn't serve my requirement.

    Then I used

    char dig = (char)(((int)'0')+ (-32));
    
    it gave an invalid output
    

    Kindly help in my requirement. Thanks in advance