1

If I have an integer that will have always a positive number less than 16 , can I just cast it to byte

int i = 5;
byte b = (byte) i;

or should I have unexpected behaviour when converting it back to integer on different devices?

Thanks

Basilevs
  • 22,440
  • 15
  • 57
  • 102
Snake
  • 14,228
  • 27
  • 117
  • 250
  • What do you mean by "converting it back to integer?" And what about negative values? `Integer.MIN_VALUE` is less than 16, but cannot "fit" in a `byte`. – Matt Ball Mar 11 '14 at 01:20
  • 1
    This link will probbaly help you : http://stackoverflow.com/questions/842817/how-does-java-convert-int-into-byte – Sushil Mar 11 '14 at 01:20
  • Good point. I meant to say the number is always positive and less than 16 – Snake Mar 11 '14 at 01:25

2 Answers2

0

You could always use the Integer class and use byteValue.

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#byteValue()

which simply does

return (byte)value;
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

No, you won't get unexpected behaviour converting a byte between 0 and 15 into an int on different platforms. One of the strengths of Java is that it precisely defines what happens with such conversions, so that they are always platform independent.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110