简体   繁体   English

如何将字节字符串转换为字节[]

[英]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 ". 即我有一个字符串“ [B @ 1a758cb ”。 That is Base64 encrypted String of the main String "gunjan". 那就是主字符串“ gunjan”的Base64加密字符串。 Here for decryption I want to convert that encrypted byte string to byte[]. 为了解密,我想将加密的字节字符串转换为byte []。

But String.getByte[] is not working for me. 但是String.getByte []对我不起作用。 String.getBytes[] gives bytes of the byte String. String.getBytes []给出字节String的字节。

How can I do that ?? 我怎样才能做到这一点 ?? Do I have to iterate over each character in the byte string and to convert them to byte[] ?? 我是否必须遍历字节字符串中的每个字符并将其转换为byte []?

EDITED 已编辑

I am using Apache Coded 3.1 jar for Base64 conversion. 我正在使用Apache Coded 3.1 jar进行Base64转换。 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.. 此处base64Encoded的值为[B @ 1a758cb。您还可以在图像中看到控制台日志。 在此处输入图片说明

First of all, you don't have any problem here, since the decoded string value (gunjan) is equal to the original value (gunjan). 首先,这里没有任何问题,因为解码后的字符串值(gunjan)等于原始值(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. 如注释中所述,字符串[@Bxxxx是在字节数组上调用toString()的结果。 This desn't display the value of the bytes, but the type of the array ( [@B ) followed by the hashCode of the array object. 这不是显示字节的值,而是显示数组的类型( [@B ),后跟数组对象的hashCode。 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. 此编码可能无法支持String中的每个字符。 You should use a specific encoding that supports every character on earth, like UTF8: 您应该使用支持地球上每个字符的特定编码,例如UTF8:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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