4

I need to send some bytes over UDP Protocol the start squence is 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF

When I define like this:

byte [] begin = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; 

I get an error saying I need to cast those to byte type. Far as I know 0xFF doesn't exced the byte type so what is the problem ?

If i write this it works :

byte [] begin = {(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF};
SethO
  • 2,703
  • 5
  • 28
  • 38
opc0de
  • 11,557
  • 14
  • 94
  • 187
  • http://stackoverflow.com/questions/1677957/why-byte-b-byte-0xff-is-equals-to-integer-1 take a look – Ghokun Jun 28 '12 at 06:39

2 Answers2

12

Far as I know 0xFF doesn't exced the byte type so what is the problem ?

Actually it does. Bytes are signed in Java, so the range is -0x80 to 0x7f (inclusive).

(The fact that the byte type is signed is a pain in the neck, but there we go...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Any literal number in java is compiled as an int. Even if it's declared in a situation like here, where a byte is the expected value. The cast is the thing which actually transforms that literal int into a byte.

Erica
  • 2,251
  • 16
  • 21
  • Except that there's an implicit conversion from a constant `int` expression within the range of `byte` to `byte` itself. The problem is that `0xff` isn't within the range of `byte`. Try it with (say) `0x7f` and you don't need the cast. – Jon Skeet Jun 28 '12 at 08:24