简体   繁体   中英

Conversion Between ByteArray and String

I am having a 2D Byte array which is like this :

Byte [][] headerparts=new Byte[n+1][24];

Now i have a String array too :

String[] finalshares=new String[n];

I need to convert Byte array to string array .So i did somewhat like this :

for(i=0;i<n;i++){
    finalshares[i]=headerparts[i].toString();
}

Is this correct way to do this ?

Also how to convert back this String array to a 2D Byte array.Please help.

Is it right for a String to Bytearray Like this :

for(i=0;i<n;i++){
    System.out.println(finalshares[i].getBytes());
}

EDIT : I made conversion according to answer provided below :

The problem is say initially my 2D[][] Byte array is :

 1 5 3 116 69 75 99 54 0 0 0 106 115 71 69 108 49 122 0 0 0 44 40 
 2 5 3 116 0 0 0 54 105 97 0 106 115 71 0 0 0 122 86 0 0 44 40 
 3 5 0 0 69 75 0 54 0 97 53 106 0 0 69 108 0 122 0 0 0 44 0 
 4 0 3 0 69 0 99 0 105 97 53 0 115 0 69 0 49 0 86 0 0 0 40 
 5 0 0 116 0 75 99 0 105 0 53 0 0 71 0 108 49 0 86 0 0 0 0 

Then why the final answer after converting String [][] to Bytes not same to this.?

The final answer comes to be :

 [B@17bd6a1
 [B@147ee05
 [B@15b9e68
 [B@1fcf0ce
 [B@1256ea2

Use byte array instead of Byte Array

Byte array to string array:

for(i=0;i<n;i++){
    finalshares[i]=new String(headerparts[i]);
}

String to Bytearray:

for(i=0;i<n;i++){
headerparts[i] = finalshares[i].getBytes();

}

You can convert your byte array to a String object by passing the byte array as an argument to the String constructor. Try doing it this way (for this you need to use byte[] rather than it's wrapper class Byte[]),

for(i=0;i<n;i++){
    finalshares[i]=new String(headerparts[i]); // Java converts it to a string representation
}

You can also use the constructor:

new String(byte[] bytes, Charset charset)

if you know the nature of the bytes being passed on (whether you are using ASCII, UTF-8 etc.).

The toString() method that you have used will return a default implementation of the byte array conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM