将Java字符串转换为字节数组 [英] Convert Java string to byte array

查看:195
本文介绍了将Java字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,我正在加密,然后转换成一个字符串,以便它可以传输。当我收到字符串时,我必须将字符串转换回一个字节数组,以便它可以被解密。我检查了接收到的字符串是否匹配发送的字符串(包括长度),但是当我使用像str.getBytes()这样的东西将其转换为字节数组时,它与我的原始字节数组不符。



示例输出:

  SENT:WzShnf / fOV3NZO2nqnOXZbM1lNwVpcq3qxmXiiv6M5xqC1A3 
SENT STR:[B @ 3e4a9a7d
RECEIVED STR:[B @ 3e4a9a7d
Received:W0JAM2U0YTlhN2Q =

any想法如何将接收到的字符串转换成与发送的字节数组匹配的字节数组?



谢谢

解决方案

你使用 array.toString(),实现如下:

  return[B @+ Integer.toString(this.hashCode(),16); 

(实际上它继承了Object的定义,而 @ 只是 getClass()的结果。getName()。)



而这里的hashCode并不取决于内容。



而是使用新的String(数组,编码)。



当然,这只适用于字符串,这些字节数组真正可以表示为Java字符串(包含可读字符),而不适用于任意数组。有更好的使用base64,如Bozho推荐(但请确保在频道的两边使用它)。


I have a byte array which I'm encrypting then converting to a string so it can be transmitted. When I receive the string I then have to convert the string back into a byte array so it can be decrypted. I have checked that the received string matches the sent string (including length) but when I use something like str.getBytes() to convert it to a byte array, it does not match my original byte array.

example output:

SENT: WzShnf/fOV3NZO2nqnOXZbM1lNwVpcq3qxmXiiv6M5xqC1A3
SENT STR: [B@3e4a9a7d
RECEIVED STR: [B@3e4a9a7d
RECEIVED: W0JAM2U0YTlhN2Q=

any ideas how i can convert the received string to a byte array which matches the sent byte array?

Thanks

解决方案

You used array.toString(), which is implemented like this:

return "[B@" + Integer.toString(this.hashCode(), 16);

(In fact it inherits the definition from Object, and the part before the @ simply is the result of getClass().getName().)

And the hashCode here does not depend on the content.

Instead, use new String(array, encoding).

Of course, this only works for byte-arrays which are really representable as Java strings (which then contain readable characters), not for arbitrary arrays. There better use base64 like Bozho recommended (but make sure to use it on both sides of the channel).

这篇关于将Java字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆