2012-03-24 21 views

risposta

12

Sembra un lavoro per lo ByteBuffer.

Un po 'come

public static void main(String[] args) { 
    byte[] payload = toArray(-1991249); 
    int number = fromArray(payload); 
    System.out.println(number); 
} 

public static int fromArray(byte[] payload){ 
    ByteBuffer buffer = ByteBuffer.wrap(payload); 
    buffer.order(ByteOrder.BIG_ENDIAN); 
    return buffer.getInt(); 
} 

public static byte[] toArray(int value){ 
    ByteBuffer buffer = ByteBuffer.allocate(4); 
    buffer.order(ByteOrder.BIG_ENDIAN); 
    buffer.putInt(value); 
    buffer.flip(); 
    return buffer.array(); 
} 
+0

Correggetemi se ho torto, ma se faccio 'int value = buffer.getInt();' allora int potrebbe non essere in grado di contenere l'intero numero (se non è firmato e non è firmato) . – Aviram

+0

@Aviram Un numero intero in Java è di 32 bit (4 byte), a condizione che il ByteBuffer sia lungo 4 byte, non vedo perché dovrebbe esserci un problema. Ho migliorato la mia risposta e l'ho testata con i positivi e i negativi e funziona fino ad ora. Posso perdere qualcosa? Se si intende utilizzare numeri interi non firmati, utilizzare long e non numeri interi, poiché gli interi in Java sono firmati. –

+3

Puoi usare 'return buffer.getInt() & 0xFFFFFFFFL;' come sempre otterrai il valore senza segno. I ByteBuffer sono BIG_ENDIAN per impostazione predefinita. Non è necessario chiamare 'flip()' per usare 'array()' –

8

È possibile utilizzare ByteBuffer, oppure è possibile farlo nel modo antiquato:

long result = 0x00FF & byteData[0]; 
result <<= 8; 
result += 0x00FF & byteData[1]; 
result <<= 8; 
result += 0x00FF & byteData[2]; 
result <<= 8; 
result += 0x00FF & byteData[3];