3

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

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Just a note that it's a good idea to specify what encoding you want to use when creating a String from raw bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.