Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte type is weird

Tags:

java

android

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};
like image 985
opc0de Avatar asked Oct 16 '25 16:10

opc0de


2 Answers

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...)

like image 79
Jon Skeet Avatar answered Oct 18 '25 08:10

Jon Skeet


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.

like image 31
Erica Avatar answered Oct 18 '25 08:10

Erica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!