如何转换的ByteBuffer到Integer和String? [英] How to convert from ByteBuffer to Integer and String?

查看:783
本文介绍了如何转换的ByteBuffer到Integer和String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的ByteBuffer的 putInt()方法转换的 INT 字节数组。我该怎么做相反?因此,这些字节转换为int?

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?

另外,我转换的字符串使用String的的getBytes()方法的字节数组。如何转换它的其他方式轮?在 bytesArray.getString()不会返回一个可读的字符串。我得到的东西像 BF @ DDAD

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

推荐答案

您可以使用 ByteBuffer.getInt 方法,指定在该整数发生偏移,转换一系列字节成整数。另外,如果你碰巧知道的字节顺序,可以使用按位运算符从它的8位八位明确重建的32位整数。

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

这篇关于如何转换的ByteBuffer到Integer和String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆