Writing unsigned int of 4 bytes over network

拈花ヽ惹草 提交于 2019-12-03 08:27:33

Just use DataOutput/InputStream.

To write, cast your long to int

public void writeUInt32(
      long uint32,
      DataOutputStream stream
    ) throws IOException
{
    stream.writeInt( (int) uint32 );
}

On read, use readInt, assign to long and mask top 32 bits to get unsigned value.

public long readUInt32(
      DataInputStream stream
    ) throws IOException
{
    long retVal = stream.readInt( );

    return retVal & 0x00000000FFFFFFFFL;
}

EDIT

From your questions, looks like you are confused about Java cast conversions and promotions for primitive types.

Read this section of Java Spec on Conversions and Promotions: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!