how example ejemplo definicion array java arrays integer byte

example - Convertir entero en matriz de bytes(Java)



how to array in java (8)

¿Cuál es una forma rápida de convertir un Integer en una Byte Array ?

por ejemplo, 0xAABBCCDD => {AA, BB, CC, DD}


Echa un vistazo a la clase ByteBuffer .

ByteBuffer b = ByteBuffer.allocate(4); //b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN. b.putInt(0xAABBCCDD); byte[] result = b.array();

Establecer el orden de bytes asegura que el result[0] == 0xAA , result[1] == 0xBB , result[2] == 0xCC y result[3] == 0xDD .

O, alternativamente, puede hacerlo manualmente:

byte[] toBytes(int i) { byte[] result = new byte[4]; result[0] = (byte) (i >> 24); result[1] = (byte) (i >> 16); result[2] = (byte) (i >> 8); result[3] = (byte) (i /*>> 0*/); return result; }

Sin ByteBuffer clase ByteBuffer se diseñó para tareas tan sucias. De hecho, el java.nio.Bits privado define estos métodos auxiliares que ByteBuffer.putInt() utiliza:

private static byte int3(int x) { return (byte)(x >> 24); } private static byte int2(int x) { return (byte)(x >> 16); } private static byte int1(int x) { return (byte)(x >> 8); } private static byte int0(int x) { return (byte)(x >> 0); }


Es mi solución:

public void getBytes(int val) { byte[] bytes = new byte[Integer.BYTES]; for (int i = 0;i < bytes.length; i ++) { int j = val % Byte.MAX_VALUE; bytes[i] = (j == 0 ? Byte.MAX_VALUE : j); } }

No probé este código, pruébalo, por favor.
Escribir resultado en comentarios


Esto te ayudará

importar java.nio.ByteBuffer; importar java.util.Arrays;

public class MyClass { public static void main(String args[]) { byte [] hbhbytes = ByteBuffer.allocate(4).putInt(16666666).array(); System.out.println(Arrays.toString(hbhbytes)); } }


Puedes usar BigInteger :

De enteros:

byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray(); System.out.println(Arrays.toString(array)) // --> {-86, -69, -52, -35 }

La matriz devuelta tiene el tamaño que se necesita para representar el número, por lo que podría ser del tamaño 1, para representar 1, por ejemplo. Sin embargo, el tamaño no puede ser más de cuatro bytes si se pasa una int.

De cadenas:

BigInteger v = new BigInteger("AABBCCDD", 16); byte[] array = v.toByteArray();

Sin embargo, deberá tener cuidado, si el primer byte es más alto 0x7F (como en este caso), donde BigInteger insertaría un byte 0x00 al comienzo de la matriz. Esto es necesario para distinguir entre valores positivos y negativos.


Si te gusta la Guava , puedes usar su clase Ints :

Para intbyte[] , use toByteArray() :

byte[] byteArray = Ints.toByteArray(0xAABBCCDD);

El resultado es {0xAA, 0xBB, 0xCC, 0xDD} .

Su reverso es fromByteArray() o fromBytes() :

int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD}); int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);

El resultado es 0xAABBCCDD .


Usando BigInteger :

private byte[] bigIntToByteArray( final int i ) { BigInteger bigInt = BigInteger.valueOf(i); return bigInt.toByteArray(); }

Usando DataOutputStream :

private byte[] intToByteArray ( final int i ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(i); dos.flush(); return bos.toByteArray(); }

Usando ByteBuffer :

public byte[] intToBytes( final int i ) { ByteBuffer bb = ByteBuffer.allocate(4); bb.putInt(i); return bb.array(); }


usa esta función, me funciona

public byte[] toByteArray(int value) { return new byte[] { (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value}; }

traduce el int en un valor byte


static byte[] toBytes(int val, int bufferSize) { byte[] result = new byte[bufferSize]; for(int i = bufferSize - 1; i >= 0; i--) { result[i] = (byte) (val /*>> 0*/); val = (val >> 8); } return result; }

// por jordaoesa e samirtf - mejores amigos JFL <3