java - 如何在 java 中将 Long 转换为 byte[] 并返回

标签 java type-conversion byte long-integer

如何在 Java 中将 long 转换为 byte[] 并返回?

我正在尝试将 long 转换为 byte[],以便我能够通过TCP 连接。另一方面,我想获取 byte[] 并将其转换回 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();
}

或者包装在一个类中以避免重复创建 ByteBuffer:

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解决方案。我认为我的答案真正的主要目的是您不必担心系统的字节顺序。

关于java - 如何在 java 中将 Long 转换为 byte[] 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937242/

相关文章:

java - Weblogic 凭证解密问题

java - 如何使用 CodeModel 的 JExpr.plus 方法删除不必要的括号?

r - 在 R 中将 DNA 序列转换为时间序列

c - 整体提升/转换:为什么我要关心结果类型的名称?

c - 如何从十六进制值中提取低位字节?

byte - Libgdx Pixmap 和 getFrameBufferPixels

byte - CRC32 STM 32 上的 CRC 外设 : byte and word streams of same data give different results

java - TopComponent 中动态添加的组件不会显示

java - Preffix_Suffix 设置为 int 数组 [编程]

java - 将字符串转换为 key