2010-02-02 19 views
148

ho ottenuto un numero intero: 1695609641Java integer a byte

quando uso il metodo:

String hex = Integer.toHexString(1695609641); 
system.out.println(hex); 

dà:

6510f329 

ma voglio un array di byte:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29}; 

Come posso fare questo?

+4

possibile duplicato del [Convertire intero in array di byte (Java)] (http://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java) – finnw

risposta

248

usando Java NIO ByteBuffer è molto semplice:

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array(); 

for (byte b : bytes) { 
    System.out.format("0x%x ", b); 
} 

uscita:

 
0x65 0x10 0xf3 0x29 
+3

Oppure usa il formato '" 0x% 02X "' se vuoi sempre due caratteri esadecimali come esadecimali maiuscoli, ad es. 'System.out.format (" 0x% 02X ", (byte) 10)' visualizza '0x0A'. –

+0

ByteBuffer.allocate() non sembra esistere ma allocateDirect() lo fa. Sto andando con quello. – conor

+0

@conor Javadoc dice che allocateDirect() ha un costo e dovrebbe essere usato quando un buffer viene mantenuto per un po '. Anche se la risposta funziona sembra essere un po 'eccessivo per il caso d'uso a portata di mano. –

0
integer & 0xFF 

per il primo byte

(integer >> 8) & 0xFF 

per il secondo ed il ciclo ecc, la scrittura in un array di byte preallocato. Un po 'disordinato, sfortunatamente.

123

ne dite:

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

L'idea è non mia. L'ho preso da some post on dzone.com.

+2

-1 Non è una buona idea scrivere a mano le cose come questo; questo è ciò che le librerie JDK correttamente testate e revisionate sono per. –

+40

Vedo il tuo punto, ma per questo particolare compito il mio codice è più dichiarativo e chiaro di un ByteBuffer "magico", che deve controllare per vedere che cosa fa. –

+22

@Kevin - questo è molto duro - ci sono molti casi in cui questo tipo di codice è appropriato, ad es. nell'elaborazione delle immagini. Le librerie JDK sono grandi in generale, ma non coprono e/o non sono ottimizzate per tutti i casi d'uso. – mikera

5
byte[] conv = new byte[4]; 
conv[3] = (byte) input & 0xff; 
input >>= 8; 
conv[2] = (byte) input & 0xff; 
input >>= 8; 
conv[1] = (byte) input & 0xff; 
input >>= 8; 
conv[0] = (byte) input; 
+0

Mi chiedo, qual è il punto di '& 0xFF'? –

+0

Questo estrae gli 8 byte meno significativi. Evita anche di trascinare il segno del numero di input nell'ottetto convertito. –

+0

http://stackoverflow.com/questions/35305634/how-to-write-this-c-sharp-four-bytes-of-length-info-in-java - puoi per favore risolvere questo C# in Java? – YumYumYum

38

BigInteger.valueOf(1695609641).toByteArray()

+2

quale garanzia hai che quello produrrà un Array di 4 byte? – MeBigFatGuy

+1

Esattamente quello che ha scritto MeBigFatGuy. Javadoc di 'BigInteger.toByteArray()' afferma: "La matrice conterrà il numero minimo di byte richiesto per rappresentare questo BigInteger ..." – icza

+2

Dove nella domanda chiede che la matrice di byte sia di lunghezza fissa 4? A seconda dell'algoritmo che si intende far parte di voi è possibile utilizzare la lunghezza dell'array – vmpn

1

I org.apache.hadoop.hbase.util.Bytes classe ha un mucchio di utili metodi di conversione di byte [], ma potresti non voler aggiungere l'intero jar HBase t o il tuo progetto solo per questo scopo. È sorprendente che non solo tale metodo manchi AFAIK dal JDK, ma anche da libs ovvie come commons io.

4

I blocchi sotto funzionano almeno per l'invio di un int su UDP.

int array di byte:

public byte[] intToBytes(int my_int) throws IOException { 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    ObjectOutput out = new ObjectOutputStream(bos); 
    out.writeInt(my_int); 
    out.close(); 
    byte[] int_bytes = bos.toByteArray(); 
    bos.close(); 
    return int_bytes; 
} 

array di byte a int:

public int bytesToInt(byte[] int_bytes) throws IOException { 
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes); 
    ObjectInputStream ois = new ObjectInputStream(bis); 
    int my_int = ois.readInt(); 
    ois.close(); 
    return my_int; 
} 
+4

l'uso di ObjectOutputStream non è corretto. Usa DataOutputStream, l'uso di OOS lo rende così l'array di byte non è 4 byte. – MeBigFatGuy

4
public static byte[] intToBytes(int x) throws IOException { 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    DataOutputStream out = new DataOutputStream(bos); 
    out.writeInt(x); 
    out.close(); 
    byte[] int_bytes = bos.toByteArray(); 
    bos.close(); 
    return int_bytes; 
} 
1

La mia prova:

public static byte[] toBytes(final int intVal, final int... intArray) { 
    if (intArray == null || (intArray.length == 0)) { 
     return ByteBuffer.allocate(4).putInt(intVal).array(); 
    } else { 
     final ByteBuffer bb = ByteBuffer.allocate(4 + (intArray.length * 4)).putInt(intVal); 
     for (final int val : intArray) { 
      bb.putInt(val); 
     } 
     return bb.array(); 
    } 
} 

Con esso si può fare questo:

012.
byte[] fourBytes = toBytes(0x01020304); 
byte[] eightBytes = toBytes(0x01020304, 0x05060708); 

classe completa è qui: https://gist.github.com/superbob/6548493, supporta l'inizializzazione da corti o lunghi

byte[] eightBytesAgain = toBytes(0x0102030405060708L); 
18
byte[] IntToByteArray(int data) { 

byte[] result = new byte[4]; 

result[0] = (byte) ((data & 0xFF000000) >> 24); 
result[1] = (byte) ((data & 0x00FF0000) >> 16); 
result[2] = (byte) ((data & 0x0000FF00) >> 8); 
result[3] = (byte) ((data & 0x000000FF) >> 0); 

return result; 
} 
16

Utilizzando Guava:

byte[] bytearray = Ints.toByteArray(1695609641);