Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 953
darksky Avatar asked Feb 21 '26 12:02

darksky


1 Answers

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);
like image 102
templatetypedef Avatar answered Feb 23 '26 01:02

templatetypedef