栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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解决方案考虑此答案。我认为我的答案真正要解决的主要问题是,你不必自己担心系统的字节序。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号