Literal Syntax For byte[] arrays using Hex notation..?

后端 未结 4 1975

The compiler seems to be ok with this (single digit hex values only):

byte[] rawbytes={0xa, 0x2, 0xf};

But not this:

byte[]         


        
4条回答
  •  难免孤独
    2020-12-05 13:35

    "0xFF" is an int literal for the decimal value 255, which isn't representable as a byte.

    For now, you'll need to cast it to a byte to tell the compiler you really mean -1, like this:

    byte[] rawbytes = { 0xA, 0x2, (byte) 0xFF };
    

    It was proposed to add a new byte literal syntax (y or Y suffix) to Java 7. Then you would have been able to write:

    byte[] rawbytes = { 0xA, 0x2, 0xFFy };
    

    However, this proposal was not included in the "omnibus proposal for improved integral literals," so we be stuck with the cast forever.

提交回复
热议问题