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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I was hoping this was true. I was just skeptical about it after reading this post: stackoverflow.com/questions/14531235/…. 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?
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.
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[].
"... does this mean that byte instances are different than bytes in an array?" - Clearly yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.