美文网首页
long与byte[]的相互转换

long与byte[]的相互转换

作者: lodtap | 来源:发表于2020-12-22 14:10 被阅读0次

//long类型转byte[]

//分配缓冲区,单位为字节,long类型占8字节,所以设置为8 

 private static ByteBuffer buffer = ByteBuffer.allocate(8); 

 //long类型转byte[] 

 public static byte[] longToBytes(long x) { buffer.putLong(0, x); return buffer.array(); }

//byte[]转long类型 

 public static long bytesToLong(byte[] bytes) {

     buffer.put(bytes, 0, bytes.length);

     //flip方法将Buffer从写模式切换到读模式,调用flip()方法会将position设回0,从头读起 

    buffer.flip(); 

     return buffer.getLong();

 }

相关文章

网友评论

      本文标题:long与byte[]的相互转换

      本文链接:https://www.haomeiwen.com/subject/fsajnktx.html