How to Specify a Byte Literal in Java

How do you specify a byte literal in Java?

You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.

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

As the other answered already said, byte is a signed type in Java. The range is from -128 to 127 inclusive. So 0xff is equal to -0x01. You can use 0xff instead of -0x01 if you add a manual cast:

byte[] rawbytes={0xa, 0x2, (byte) 0xff};

How to specify a constant is a byte or short?

What you are actually talking about is an integer literal ( 1 ) versus a long literal ( 1L ). There is actually no such thing as a short or byte literal in Java. But it usually doesn't matter, because there is an implicit conversion from integer literals to the types byte, short and char. Thus:

final byte one = 1;  // no typecast required.

The implicit conversion is only allowed if the literal is in the required range. If it isn't you need a type cast; e.g.

final byte minusOne = (byte) 255;  // the true range of byte is -128 .. +127

There are other cases where an explicit conversion is needed; e.g. to disambiguate method overloads, or to force a specific interpretation in an expression. In such cases you need to use a cast to do the conversion.

Your example is another of those cases.


But the bottom line is that there is no Java syntax for expressing byte or short literals.

Java binary literals - Value -128 for byte

According to the Java Specification,

http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1

all your declarations (b, b1,..., and b8) use int literals, even when they would fit in a byte. There's no byte literal in Java, you can only use an int to initialize a byte.

I did some tests and byte neg128 = -0b1000_0000; works fine. 0b1000_0000 is 128, so you just need to put a - sign before it. Notice that that 1 is not a sign bit at all (don't think about 8-bit bytes, think about 32-bit ints converted to bytes). So if you want to specify the sign bit you need to write all 32 bits, as you have demonstrated.

So byte b8 = 0b1000_0000; is an error just like byte b8 = 128; is an error (+128 does not fit in a byte). You can also force the conversion with a cast:

byte b = (byte) 0b1000_0000;
or
byte b = (byte) 128;

The cast tells the compiler that you know 128 does not fit in a byte and the bit-pattern will be reinterpreted as -128.

How to represent 11111111 as a byte in java

You need to cast the value to a byte:

byte b = (byte) 0b11111111;

The reason you need the cast is that 0b11111111 is an int literal (with a decimal value of 255) and it's outside the range of valid byte values (-128 to +127).

Why are there no byte or short literals in Java?

In C, int at least was meant to have the "natural" word size of the CPU and long was probably meant to be the "larger natural" word size (not sure in that last part, but it would also explain why int and long have the same size on x86).

Now, my guess is: for int and long, there's a natural representation that fits exactly into the machine's registers. On most CPUs however, the smaller types byte and short would have to be padded to an int anyway before being used. If that's the case, you can as well have a cast.

JAVA: why binary literal for byte with negative sign is being considered as integer type?

You can safely assign a values from -2^7 to 2^7-1 (-128 to 127) to a byte ,since it is 8 bits.

where as 0b1111_1111 = 255

So need a cast there

 byte mask = (byte) 0b1111_1111;

Passing method arguments to the method parameters of type byte,int,int in java

Your question boils down to:

Why does assigning 15 to a byte works in a variable declaration:

byte b = 15;

But not when calling a method?

subtractNumbers(15,16,17);

This is because those two situations are in two different contexts. The first is in an assignment context, while the second is in an invocation context.

According to the JLS §5.2 Assignment Contexts,

Assignment contexts allow the use of one of the following:

...

In addition, if the expression is a constant expression (§15.28) of
type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is
    representable in the type of the variable.

15 is certainly a constant expression, so a narrowing primitive conversion from int to byte is allowed.

In an invocation context however, this is not true:

JLS §5.3 Invocation Context

Strict invocation contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)

Loose invocation contexts allow a more permissive set of conversions,
because they are only used for a particular invocation if no
applicable declaration can be found using strict invocation contexts.
Loose invocation contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by widening reference conversion
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion

"narrowing primitive conversion" is not mentioned, so it is not allowed in invocation contexts.

How do I initialize a byte array in Java?

You can use an utility function to convert from the familiar hexa string to a byte[].
When used to define a final static constant, the performance cost is irrelevant.

Since Java 17

There's now java.util.HexFormat which lets you do

byte[] CDRIVES = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d");

This utility class lets you specify a format which is handy if you find other formats easier to read or when you're copy-pasting from a reference source:

byte[] CDRIVES = HexFormat.ofDelimiter(":")
.parseHex("e0:4f:d0:20:ea:3a:69:10:a2:d8:08:00:2b:30:30:9d");

Before Java 17

I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?

byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");

I insert it here for maximum readability :

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}


Related Topics



Leave a reply



Submit