0

Since I found out that it's impossible to have unsigned bytes in java, and that essentially they take up the same memory as an int, is there really any difference when you send them over a packet?

If I send a Java byte via tcp or udp via(Games.RealTimeMultiplayer.sendReliableMessage) would that be more beneficial to me than just sending an integer to represent an unsigned byte?

Andrew
  • 3,393
  • 4
  • 25
  • 43

1 Answers1

3

Since I found out that it's impossible to have unsigned bytes in java

This is incorrect. There are lots of ways. You can even use byte to represent an unsigned byte. You just need to perform a mapping in places that require it; e.g.

    byte b = ...
    int unsigned = (b >= 0) ? b : (b + 256);

... and that essentially they take up the same memory as an int.

That is also incorrect. It is true for a byte variable or field. However, the bytes in a byte array occupy 1/4 of the space of integers in an int array.

... is there really any difference when you send them over a packet?

Well yes. A byte sent over the network (in the natural fashion) takes 1/4 of the number of bits as an int sent over the network. If you are sending an "8 bit quantity" as 32 bits, then you are wasting network bandwidth.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks I was hoping this was true. I was just skeptical about it after reading this post: http://stackoverflow.com/questions/14531235/in-java-is-it-more-efficient-to-use-byte-or-short-instead-of-int-and-float-inst. Hence the statement `So when you declare a local variable or object field as (say) a byte, the variable / field will be stored in a 32 bit cell, just like an int.`. I read this with a couple other articles and was feeling quite daunted. Can you explain a little further `the bytes in a byte array occupy 1/4 `, does this mean that byte instances are different than bytes in an array? – Andrew Mar 13 '15 at 15:57
  • I'm sorry you are feeling daunted. However, these things are FACTS, and I could even find the relevant parts of the JVM specification that support this. – Stephen C Mar 13 '15 at 22:44
  • JVMS 2.5. and 2.6 cover how variables are held in Stack Frames. The rest is (AFAIK) implementation specific. However, AFAIK, all Java implementations with use a one 32bit word to hold a byte for a `byte` variable, and will pack 4 bytes into each 32bit word in a `byte[]`. – Stephen C Mar 13 '15 at 22:59
  • *"... does this mean that byte instances are different than bytes in an array?"* - Clearly yes. – Stephen C Mar 13 '15 at 23:02