Convert Java string to byte array

前端 未结 4 1159
旧巷少年郎
旧巷少年郎 2020-12-06 01:25

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

4条回答
  •  鱼传尺愫
    2020-12-06 01:51

    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).

提交回复
热议问题