Long To Byte Array Java

Long To Byte Array Java | In this post, we will write a Java program to convert long to byte array. The long and byte are primitive data types supported by the Java programming language. To convert long to byte array in Java we can use two methods:-

1) By Using Shift Operations
Shift operations are the type of operation available in java, there are many types of shift operations like signed left shift, Signed right shift, unsigned left shift, and unsigned right shift.

For this program we use a signed right shift, the right shift operator moves all the bits to the right by a given position.

2) By Using DataOutputSteam
Java uses DataOutputStream to write data that can be read by a data input stream. The data output stream class allows an application to write primitive data types to the output stream in a machine-independent language.

Let us see the demonstrations of the Java long to byte array program using shift operations, and then by using DataOutputStream.

Long To Byte Array Java Using Signed Right Shift Operations

import java.util.Arrays;

public class Main {

   private static Byte[] longtoBytes(long data) {
      return new Byte[] { (byte) ((data >> 56) & 0xff),
        (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff),
        (byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff),
        (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff),
        (byte) ((data >> 0) & 0xff), };
   }

   public static void main(String args[]) {
      Long array = 12234567l;
      Byte[] bytes = longtoBytes(array);
      System.out.println(Arrays.toString(bytes));
   }
}

Output:-

[0, 0, 0, 0, 0, -70, -81, 71]

In the above long to byte array Java program, we took a long value of 12234567L and converted it into the Byte array. Instead of Wrapper classes, you can also take the primitives.

Java Long to Byte Array By Using DataOutputStream

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Main {
   public static byte[] longToByteArray(final long i) throws IOException {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(bos);
      dos.writeLong(i);
      dos.flush();
      return bos.toByteArray();
   }

   public static void main(String args[]) throws IOException {
      Long array = 12234567l;
      byte[] bytes = longToByteArray(array);
      System.out.println(Arrays.toString(bytes));
   }
}

Output:-

[0, 0, 0, 0, 0, -70, -81, 71]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *