2009-11-17 14 views
30

he declarado una matriz de bytes (estoy usando Java):Cómo imprimir bytes en hexadecimal usando System.out.println?

byte test[] = new byte[3]; 
test[0] = 0x0A; 
test[1] = 0xFF; 
test[2] = 0x01; 

¿Cómo podría imprimir los diferentes valores almacenados en la matriz?

Si uso System.out.println (prueba [0]) se imprimirá '10'. Me gustaría imprimir 0x0A

Gracias a todos!

Respuesta

56
System.out.println(Integer.toHexString(test[0])); 

O (impresión bastante)

System.out.printf("0x%02X", test[0]); 

O (impresión bastante)

System.out.println(String.format("0x%02X", test[0])); 
+4

+1 para dar el ejemplo printf. –

+2

De todos estos, el 'System.out.printf' es probablemente la mejor idea. – abyx

+0

muy útil, pulgares arriba –

2
byte test[] = new byte[3]; 
test[0] = 0x0A; 
test[1] = 0xFF; 
test[2] = 0x01; 

for (byte theByte : test) 
{ 
    System.out.println(Integer.toHexString(theByte)); 
} 

NOTA: test [1] = 0xFF; esto no compilará, no puedes poner 255 (FF) en un byte, java querrá usar un int.

es posible que pueda hacer ...

test[1] = (byte) 0xFF; 

que había prueba si estaba cerca de mi IDE (si estaba cerca de mi IDE que wouln't estar en Stackoverflow)

+0

Definitivamente puede hacer byte b = 255 & 0xFF; Y luego al leerlo int cálculo = (0xFF & b) + 5; para volver a leer 255 –

7
for (int j=0; j<test.length; j++) { 
    System.out.format("%02X ", test[j]); 
} 
System.out.println(); 
Cuestiones relacionadas