tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Articles > Java > Basics > How to convert Long to Byte Array

How to convert Long to Byte Array 

The following example shows converting a Long to Byte array. Since a Java Long occupies 8 bytes allocate a ByteBuffer of capacity 8 and write the Long to ByteBuffer. It updates the ByteBuffer with 8 bytes representing the Long. Finally convert the ByteBuffer to byte array.

java.nio.ByteBuffer
  • public static ByteBuffer allocate(int capacity)
    Allocates a new byte buffer of given capacity.
  • public ByteBuffer putLong(long value)
    Writes eight bytes containing the given long value to this ByteBuffer.
  • public final byte[] array()
    Returns the ByteBuffer as byte array.

File Name  :  
com/bethecoder/articles/basics/prim2bytea/Long2ByteArrayTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.articles.basics.prim2bytea;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Long2ByteArrayTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    //Since long occupies 8 bytes allocate a buffer of size 8
    byte [] bytes = ByteBuffer.allocate(8).putLong(1729172917291729L).array();
    System.out.println(Arrays.toString(bytes));
  }

}
   

It gives the following output,
[0, 6, 36, -84, 113, 125, -118, -47]


                    Print

   



Books Recommendation

 
 
bl  br