Network Order short (Java)

后端 未结 3 1613
旧巷少年郎
旧巷少年郎 2021-01-20 04:04

I need to send a Network Order short for a game server I\'m writing using Java. I read about network order, but I couldn\'t find any details about a short that is sent befor

3条回答
  •  醉梦人生
    2021-01-20 04:33

    In java, a short int is a 2 byte quantity. Network byte order send the high-order byte first, followed by the next highest-order byte and so on, with the low order byte sent last. If you have an OutputStream o, and a short i, then

    o.write((i >> 8) & 0xff);
    o.write(i & 0xff);
    

    send the short in network byte order. I recommend using a DataOutputStream which has a method writeShort() (and writeInt, writeLong, etc.) which automatically write in network byte order.

提交回复
热议问题