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

编程入门 行业动态 更新时间:2024-10-19 10:23:51
本文介绍了如何将Long转换为byte []并返回java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在Java中将long转换为字节[]并返回? 我正在尝试将long转换为byte [],以便我能够通过tcp连接发送byte []。另一方面,我想取该字节[]并将其转换回double。 任何提示都将不胜感激。

How do I convert a long to a byte[] and back in Java? 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. Any tips would be appreciated.

推荐答案

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这样的库。如果你对图书馆有一些奇怪的反对意见,你应该首先考虑这个答案,对于原生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

本文发布于:2023-06-08 21:29:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589383.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   java   Long   byte

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!