Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte[] to char[]

Tags:

java

char

byte

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

like image 560
Jeetesh Nataraj Avatar asked Oct 28 '25 03:10

Jeetesh Nataraj


2 Answers

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]);
    }
    }
}
like image 187
Sejwal Avatar answered Oct 29 '25 20:10

Sejwal


If you just need a printable representation:

String readable = Arrays.toString(byte1);

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

like image 38
Jan Avatar answered Oct 29 '25 20:10

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!