且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将Java字符串转换为字节数组

更新时间:2022-10-15 09:54:02

你使用 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).