简体   繁体   中英

How to convert byte string to byte[]

I am stuck with casting issue for converting a byte String to byte array.

ie I have a String " [B@1a758cb ". That is Base64 encrypted String of the main String "gunjan". Here for decryption I want to convert that encrypted byte string to byte[].

But String.getByte[] is not working for me. String.getBytes[] gives bytes of the byte String.

How can I do that ?? Do I have to iterate over each character in the byte string and to convert them to byte[] ??

EDITED

I am using Apache Coded 3.1 jar for Base64 conversion. Here is the code from which I am getting this encrypted text..

String in = "gunjan";
byte[] byteStr = in.getBytes();
byte[] base64Encoded = Base64.encodeBase64(byteStr);

Here the value of base64Encoded is [B@1a758cb You can also see the console log in the image.. 在此处输入图片说明

First of all, you don't have any problem here, since the decoded string value (gunjan) is equal to the original value (gunjan).

You're confused by what is printed for the intermediate byte arrays. As noted in the comments, the strings [@Bxxxx are the result of calling toString() on a byte array. This desn't display the value of the bytes, but the type of the array ( [@B ) followed by the hashCode of the array object. If you want to display the byte values, use

System.out.println(Arrays.toString(byteArray));

You have a potential bug though: you're using the default encoding to transform strings to bytes and vice-versa. This encoding might not be able to support every character in your String. You should use a specific encoding that supports every character on earth, like UTF8:

byte[] byteStr = string.getBytes("UTF8");
...
String str = new String (byteStr, "UTF8");

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