Emr*_*801 139 java byte long-integer
如何将长转换为字节[]并返回Java?我正在尝试将long转换为byte [],以便我能够通过tcp连接发送byte [].另一方面,我想取该字节[]并将其转换回double.任何提示将不胜感激.
Bra*_*ace 205
public byte[] longToBytes(long x) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(x);
return buffer.array();
}
public long bytesToLong(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.put(bytes);
buffer.flip();//need flip
return buffer.getLong();
}
Run Code Online (Sandbox Code Playgroud)
或者包装在类中以避免重复创建ByteBuffers:
public class ByteUtils {
private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
public static byte[] longToBytes(long x) {
buffer.putLong(0, x);
return buffer.array();
}
public static long bytesToLong(byte[] bytes) {
buffer.put(bytes, 0, bytes.length);
buffer.flip();//need flip
return buffer.getLong();
}
}
Run Code Online (Sandbox Code Playgroud)
由于这是如此受欢迎,我只想提一下,我认为你最好在绝大多数情况下使用像Guava这样的库.如果你对库有一些奇怪的反对意见,你应该首先考虑这个答案,首先是本机java解决方案.我认为我的答案最重要的是你不必担心系统的字节序本身.
Wyt*_*tze 75
我测试了ByteBuffer方法对普通的按位操作,但后者明显更快.
public static byte[] longToBytes(long l) {
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte)(l & 0xFF);
l >>= 8;
}
return result;
}
public static long bytesToLong(byte[] b) {
long result = 0;
for (int i = 0; i < 8; i++) {
result <<= 8;
result |= (b[i] & 0xFF);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 15
为什么需要byte []?为什么不把它写到套接字?
我假设你的意思是长而不是长,后者需要允许空值.
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
dos.writeLong(longValue);
DataInputStream dis = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
long longValue = dis.readLong();
Run Code Online (Sandbox Code Playgroud)
Mic*_*ing 15
如果你正在寻找一个快速展开的版本,这应该可以做到这一点,假设一个名为"b"的字节数组长度为8:
byte [] - > long
long l = ((long) b[7] << 56)
| ((long) b[6] & 0xff) << 48
| ((long) b[5] & 0xff) << 40
| ((long) b[4] & 0xff) << 32
| ((long) b[3] & 0xff) << 24
| ((long) b[2] & 0xff) << 16
| ((long) b[1] & 0xff) << 8
| ((long) b[0] & 0xff);
Run Code Online (Sandbox Code Playgroud)
long - > byte []与上面的完全对应
byte[] b = new byte[] {
(byte) lng,
(byte) (lng >> 8),
(byte) (lng >> 16),
(byte) (lng >> 24),
(byte) (lng >> 32),
(byte) (lng >> 40),
(byte) (lng >> 48),
(byte) (lng >> 56)};
Run Code Online (Sandbox Code Playgroud)
jus*_*tis 12
目前所有的答案都比他们需要的更复杂,我讨厌任何找到这个线程的人在没有更简洁的选择的情况下就走开。
\n您可以在一行中完成这两种转换。
\n字节[]转长:
\nByteBuffer.wrap(yourBytes).getLong();\nRun Code Online (Sandbox Code Playgroud)\n长到字节[]:
\nByteBuffer.wrap(new byte[8]).putLong(yourLong).array();\nRun Code Online (Sandbox Code Playgroud)\n
小智 6
我觉得这个方法最友好。
var b = BigInteger.valueOf(x).toByteArray();
var l = new BigInteger(b);
Run Code Online (Sandbox Code Playgroud)
您可以使用 org.apache.hadoop.hbase.util.Bytes http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html中的实现
源代码在这里:
查找 toLong 和 toBytes 方法。
我相信软件许可证允许您获取部分代码并使用它,但请验证这一点。