如何将Long转换为byte 并返回到java中

如何将一个long转换为byte []并返回到Java中? 我试图将一个长转换为一个字节[],这样我就可以通过TCP连接发送字节[]。 另一方面,我想采取该字节[]并将其转换回双。 任何提示将不胜感激。

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(); } 

或者封装在一个类中以避免重复创buildByteBuffers:

 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(); } } 

由于这种情况越来越普遍,我只想提一提,在绝大多数情况下,我认为你最好使用像番石榴这样的图书馆。 如果你有一些奇怪的反对图书馆,你应该首先考虑这个答案为本机Java解决scheme。 我认为我的答案确实有一个主要的原因,那就是你不必担心系统的端到端性。

您可以使用Google Guava的字节转换方法 。

例:

 byte[] bytes = Longs.toByteArray(12345L); 

我testing了ByteBuffer方法针对普通的按位操作,但后者明显更快。

 public static byte[] longToBytes(long l) { byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte)(l & 0xFF); l >>= 8; } return result; } public static long bytesToLong(byte[] b) { long result = 0; for (int i = 0; i < 8; i++) { result <<= 8; result |= (b[i] & 0xFF); } return result; } 

为什么你需要字节[]? 为什么不把它写到sockets?

我假设你的意思是而不是 ,后者需要允许空值。

 DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(socket.getOutputStream())); dos.writeLong(longValue); DataInputStream dis = new DataInputStream( new BufferedInputStream(socket.getInputStream())); long longValue = dis.readLong(); 

您可以使用org.apache.hadoop.hbase.util.Bytes中的实现http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html

源代码在这里:

http://grepcode.com/file/repository.cloudera.com/content/repositories/releases/com.cloudera.hbase/hbase/0.89.20100924-28/org/apache/hadoop/hbase/util/Bytes.java# Bytes.toBytes%28long 29%

寻找toLong和toBytes方法。

我相信软件许可证可以让你拿走部分代码并使用它,但请确认。

只需将一个长的DataOutputStream写入一个底层的ByteArrayOutputStream即可 。 从ByteArrayOutputStream你可以通过toByteArray()获得字节数组:

 class Main { public static byte[] long2byte(long l) throws IOException { ByteArrayOutputStream baos=new ByteArrayOutputStream(Long.SIZE/8); DataOutputStream dos=new DataOutputStream(baos); dos.writeLong(l); byte[] result=baos.toByteArray(); dos.close(); return result; } public static long byte2long(byte[] b) throws IOException { ByteArrayInputStream baos=new ByteArrayInputStream(b); DataInputStream dos=new DataInputStream(baos); long result=dos.readLong(); dos.close(); return result; } public static void main (String[] args) throws java.lang.Exception { long l=123456L; byte[] b=long2byte(l); System.out.println(l+": "+byte2long(b)); } } 

相应地适用于其他基元。

提示:对于TCP,您不需要手动input字节[]。 您将使用Socket socket及其stream

 OutputStream os=socket.getOutputStream(); DataOutputStream dos=new DataOutputStream(os); dos.writeLong(l); //etc .. 

代替。

如果你正在寻找一个快速展开版本,这应该做的伎俩,假设一个长度为8的字节数组称为“b”

 long l = ((((long) b[7]) << 56) | (((long) b[6] & 0xff) << 48) | (((long) b[5] & 0xff) << 40) | (((long) b[4] & 0xff) << 32) | (((long) b[3] & 0xff) << 24) | (((long) b[2] & 0xff) << 16) | (((long) b[1] & 0xff) << 8) | (((long) b[0] & 0xff))); 

我会增加另一个答案,这个答案是最快的答案之一(是的,甚至比接受的答案还要多),但是它不适用于每一种情况。 不过,它将适用于所有可能的情况:

您可以简单地使用string作为中间。 请注意,这会给你正确的结果,即使它看起来像使用string可能会产生错误的结果只要你知道你正在使用“正常”的string。 这是一种提高效率并使代码更简单的方法,作为回报,它必须对其操作的数据string使用一些假设。

使用这种方法的情况:如果你在ASCII表格的开头使用了一些像这些符号这样的ASCII字符,下面的代码可能会失败,但是让我们面对它 – 你可能永远不会使用它们。

使用这种方法的临:请记住,大多数人通常使用一些正常的string,没有任何不寻常的字符,然后该方法是最简单和最快的方式去。

从长到字节[]:

 byte[] arr = String.valueOf(longVar).getBytes(); 

从byte []到Long:

 long longVar = Long.valueOf(new String(byteArr)).longValue(); 
  public static long bytesToLong(byte[] bytes) { if (bytes.length > 8) { throw new IllegalMethodParameterException("byte should not be more than 8 bytes"); } long r = 0; for (int i = 0; i < bytes.length; i++) { r = r << 8; r += bytes[i]; } return r; } public static byte[] longToBytes(long l) { ArrayList<Byte> bytes = new ArrayList<Byte>(); while (l != 0) { bytes.add((byte) (l % (0xff + 1))); l = l >> 8; } byte[] bytesp = new byte[bytes.size()]; for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) { bytesp[j] = bytes.get(i); } return bytesp; } 

如果您已经在使用OutputStream写入套接字,那么DataOutputStream可能会非常适合。 这里是一个例子:

 // Assumes you are currently working with a SocketOutputStream. SocketOutputStream outputStream = ... long longValue = ... DataOutputStream dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeLong(longValue); dataOutputStream.flush(); 

对于shortintfloat等类似的方法,你可以在接收端使用DataInputStream 。