int to byte[] en Java

Posted: 23rd September 2009 by Nicolas Ardison in Java, Post recordatorio
Tags: , ,

La otra vez tenia la necesidad en Java de obtener los bytes que conforman un entero con signo (Integer) de 32 bits, para meterlos en un vector y enviarlos en un flujo de datos. Una solucion a esto, fue usar operadores binarios de corrimiento de bits.

int a = 345936243;
byte[] b=new byte[4];
b[0] = (byte) (>>24);
b[1] = (byte) ((<<8)>>24);
b[2] = (byte) ((<<16)>>24);
b[3] = (byte) ((<<24)>>24);

Si se tratara de un numero de 16 bits con signo solo se agarran los dos ultimos bytes.

int a = 135132;
byte[] b = new byte [2];
b[0] = (byte) ((<<16)>>24);
b[1] = (byte) ((<<24)>>24);

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word