Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

But not this:

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

I get a "Possible Loss of Precision found : int required : byte" error?

What am I doing wrong - or are single digit hex numbers a special case ?

Java 1.5.x.

like image 547
monojohnny Avatar asked Aug 18 '10 19:08

monojohnny


People also ask

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is byte array format?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.

What is byte literal in Java?

You can use a byte literal in Java... sort of. byte f = 0; f = 0xa; 0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.


1 Answers

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}; 
like image 95
Hendrik Brummermann Avatar answered Sep 23 '22 07:09

Hendrik Brummermann