Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int[] to byte[]

I have an array of integers which represent a RGB image and would like to convert it to a byte array and save it to a file.

What's the best way to convert an array of integers to the array of bytes in Java?

like image 696
Niko Gamulin Avatar asked Jul 06 '09 08:07

Niko Gamulin


People also ask

Can we convert int to byte in Java?

The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What happens if we convert int to byte?

When an integer value is converted into a byte, Java cuts-off the left-most 24 bits. We will be using bitwise AND to mask all of the extraneous sign bits.

Can we cast int to byte?

Yes you do. For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast.


2 Answers

As Brian says, you need to work out how what sort of conversion you need.

Do you want to save it as a "normal" image file (jpg, png etc)?

If so, you should probably use the Java Image I/O API.

If you want to save it in a "raw" format, the order in which to write the bytes must be specified, and then use an IntBuffer and NIO.

As an example of using a ByteBuffer/IntBuffer combination:

import java.nio.*; import java.net.*;  class Test {        public static void main(String [] args)         throws Exception // Just for simplicity!     {         int[] data = { 100, 200, 300, 400 };          ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);                 IntBuffer intBuffer = byteBuffer.asIntBuffer();         intBuffer.put(data);          byte[] array = byteBuffer.array();          for (int i=0; i < array.length; i++)         {             System.out.println(i + ": " + array[i]);         }     } } 
like image 94
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


Maybe use this method

byte[] integersToBytes(int[] values) {    ByteArrayOutputStream baos = new ByteArrayOutputStream();    DataOutputStream dos = new DataOutputStream(baos);    for(int i=0; i < values.length; ++i)    {         dos.writeInt(values[i]);    }     return baos.toByteArray(); }   
like image 32
Prabhu R Avatar answered Oct 06 '22 01:10

Prabhu R