How to print bytes in hexadecimal using System.out.println?

前端 未结 3 1797
野性不改
野性不改 2021-01-31 16:46

I\'ve declared a byte array (I\'m using Java):

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

How could I print the

相关标签:
3条回答
  • 2021-01-31 16:48
    System.out.println(Integer.toHexString(test[0]));
    

    OR (pretty print)

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

    OR (pretty print)

    System.out.println(String.format("0x%02X", test[0]));
    
    0 讨论(0)
  • 2021-01-31 16:52
    byte test[] = new byte[3];
    test[0] = 0x0A;
    test[1] = 0xFF;
    test[2] = 0x01;
    
    for (byte theByte : test)
    {
      System.out.println(Integer.toHexString(theByte));
    }
    

    NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.

    you might be able to do...

    test[1] = (byte) 0xFF;
    

    I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)

    0 讨论(0)
  • 2021-01-31 17:12
    for (int j=0; j<test.length; j++) {
       System.out.format("%02X ", test[j]);
    }
    System.out.println();
    
    0 讨论(0)
提交回复
热议问题