How to convert Long to byte [] and return to java

How to convert long to byte [] and vice versa in Java? I am trying to convert long to byte [] so that I can send byte [] over tcp connection. On the other hand, I want to take this byte [] and convert it to double. Any advice would be appreciated.

+86
java long-integer byte
Dec 19 '10 at 21:14
source share
10 answers
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(); } 

Or wrapped in a class to avoid creating ByteBuffers multiple times:

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



Since this is becoming so popular, I just want to mention that I think you better use a library like Guava in the vast majority of cases. And if you have a weird opposition to libraries, you should first consider this answer for your own Java solutions. I think that the main thing that my answer really goes to is that you do not need to worry about the essence of the system yourself.

+138
Dec 19 '10 at 21:25
source share

You can use byte conversion methods from Google Guava .

Example:

 byte[] bytes = Longs.toByteArray(12345L); 
+53
Jan 09 '14 at 16:47
source share

I tested the ByteBuffer method against simple bitwise operations, but the latter is much faster.

 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; } 
+44
Mar 18 '15 at 20:34
source share

Why do you need byte []? why not just write it to a socket?

I assume that you mean long, not long, the latter should have zero values.

 DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(socket.getOutputStream())); dos.writeLong(longValue); DataInputStream dis = new DataInputStream( new BufferedInputStream(socket.getInputStream())); long longValue = dis.readLong(); 
+11
Dec 19 '10 at 21:28
source share

You can use the implementation in org.apache.hadoop.hbase.util.Bytes http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html

Source code here:

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

Look for toLong and toBytes methods.

I believe the software license allows you to use portions of the code and use it, but please check this.

+4
Sep 12 '13 at 17:25
source share

Just write a long DataOutputStream with a basic ByteArrayOutputStream . From ByteArrayOutputStream you can get a byte array through 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)); } } 

Accordingly, it works for other primitives.

Tip. For TCP, you do not need byte [] manually. You will use the socket socket and its streams

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

instead.

+3
Dec 19 '10 at 22:20
source share

If you are looking for a quick deploy version, this should do the trick, assuming an array of bytes with the name "b" of length 8:

 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))); 
+3
Dec 22 '14 at 21:21
source share

I will add another answer, which is the fastest possible Χ‚ (yes, even more than the accepted answer), but it will not work for each individual case. HOWEVER, it will work for every conceivable scenario:

You can simply use String as an intermediate. Please note that this will give you the correct result, even if it seems that using String may lead to incorrect results. HOW LONG, HOW YOU KNOW, YOU WORK WITH "NORMAL" STRINGS. This is a method of increasing efficiency and simplifying the code, which in turn should use some assumptions for the rows of data on which it works.

Con when using this method:. If you are working with some ASCII characters, such as these characters at the beginning of the ASCII table, the following lines may fail, but let them come across this - you will probably never use them anyway.

About using this method: Remember that most people usually work with some normal lines without any unusual characters, and then the method is the easiest and fastest way.

from Long to byte []:

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

from byte [] to Long:

 long longVar = Long.valueOf(new String(byteArr)).longValue(); 
+3
Nov 14 '15 at 10:20
source share
  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; } 
+2
Sep 12 '13 at 15:10
source share

If you are already using an OutputStream to write to a socket, then a DataOutputStream might be a good fit. Here is an example:

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

There are similar methods for short , int , float , etc. Then you can use the DataInputStream on the receiving side.

+1
Dec 19 '10 at 21:29
source share



All Articles