How to convert from ByteBuffer to Integer and String?

拜拜、爱过 提交于 2020-01-04 06:18:31

问题


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:


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


来源:https://stackoverflow.com/questions/7395695/how-to-convert-from-bytebuffer-to-integer-and-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!