Search code examples
javaarraysstringniobytebuffer

How to convert from ByteBuffer to Integer and String?


I converted an int to a byte array using ByteBuffer's putInt() method. How do I do the opposite? So convert those bytes to an int?

Furthermore, I converted a string to an array of bytes using the String's getBytes() method. How do I convert it the other way round? The bytesArray.getString() does not return a readable string. I get things like BF@DDAD


Solution

  • You can use the ByteBuffer.getInt method, specifying the offset at which the integer occurs, to convert a series of bytes into an integer. Alternatively, if you happen to know the byte ordering, you can use bitwise operators to explicitly reconstruct the 32-bit integer from its 8-bit octets.

    To convert an array of bytes into a String, you can use the String(byte[]) constructor to construct a new String out of the byte array. For example:

    byte[] bytes = /* ... get array of bytes ... */
    String fromBytes = new String(bytes);