問題描述
如何將 long
轉換為 byte[]
并返回 Java?
How do I convert a long
to a byte[]
and back in Java?
我正在嘗試將 long
轉換為 byte[]
以便能夠通過TCP 連接.另一方面,我想把那個 byte[]
轉換回 double
.
I'm trying convert a long
to a byte[]
so that I will be able to send the byte[]
over a TCP connection. On the other side I want to take that byte[]
and convert it back into a double
.
推薦答案
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();
}
或者封裝在一個類中以避免重復創建ByteBuffers:
Or wrapped in a class to avoid repeatedly creating 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();
}
}
<小時>
由于它變得如此流行,我只想提一下,我認為在絕大多數情況下使用像 Guava 這樣的庫會更好.如果您對庫有一些奇怪的反對意見,您可能應該首先考慮 this answer 對于原生 java 解決方案.我認為我的回答真正要解決的主要問題是您不必自己擔心系統的字節序.
Since this is getting so popular, I just want to mention that I think you're better off using a library like Guava in the vast majority of cases. And if you have some strange opposition to libraries, you should probably consider this answer first for native java solutions. I think the main thing my answer really has going for it is that you don't have to worry about the endian-ness of the system yourself.
這篇關于如何將 Long 轉換為 byte[] 并返回到 java的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!