Possible Duplicate:
Literal Syntax For byte[] arrays using Hex notation..?
I am trying to create a byte array of size ‘1’ that holds the byte 0x0. In Java, can I just do something like this:
byte[] space = new byte[1];
space[0] = 0x0;
Will the hex value 0x0 be converted to its byte rep of 00000000 and store it in space[0]?
In your executing program, there is only one representation of the Java
bytevalue zero – the 8 bit 2’s complement representation of the integer zero – 8 zero bits.It doesn’t make any difference whether you express the number literal in your source code as
0(decimal) or00(octal) or0x0. They all mean exactly the same thing.So – Yes, your code does what you expect.
A simpler one line version would be:
or
or even
(The last one relies on the fact that Java byte arrays are default initialized to all zeros.)
Sort of yes. Technically (i.e. according to the JLS) what happens is this:
0x0becomes anintliteral. (The specific syntax used for the integer literal is actually immaterial at this point … so long as it is valid.)bytevalue.bytevalue is used in the initialization of the array.The implicit narrowing in step 2 is allowed because:
In layman’s terms, the compiler "knows" that there will never be any loss of information in the narrowing conversion.