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

How to convert Integer to Byte Array 

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

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

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.articles.basics.prim2bytea;

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

public class Integer2ByteArrayTest {

   @param args
  public static void main(String[] args) {
    //Since int occupies 4 bytes allocate a buffer of size 4
    byte [] bytes = ByteBuffer.allocate(4).putInt(17291729).array();


It gives the following output,
[1, 7, -39, -47]


bl  br