通过网络写入4字节的unsigned int [英] Writing unsigned int of 4 bytes over network

查看:77
本文介绍了通过网络写入4字节的unsigned int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用Java编写无符号4字节int时遇到问题.

I have problem writing an unsigned 4 bytes int in java.

在Java中写一个long值在64位MacOS和32位Linux(Ubuntu)上都有不同的结果 或者 将4字节无符号int写入网络存在问题.

Either writing a long value in java has different result on 64 bit MacOS and 32 bit Linux (Ubuntu) OR Writing to network a 4 byte unsigned int has a problem.

以下调用在我的本地OSX上完美运行

The following call works perfectly on my local OSX

writeUInt32(999999,outputstream)

读回给我999999

Reading it back gives me 999999

但是,当将应用程序部署到网络时,写入长值会导致其他随机数(我假设字节序已转换?),而读取它会给我带来其他大数.

However when the application is deployed to a network writing a long value results in some other random number (I assume the endian has been switched?) and reading it gives me some other large number.

----------完整的方法栈如下-----------------

---------- The complete method stack is as below---------------

public void writeUInt32(long uint32,DataOutputStream stream) throws IOException {
        writeUInt16((int) (uint32 & 0xffff0000) >> 16,stream);
        writeUInt16((int) uint32 & 0x0000ffff,stream);
    }

public void writeUInt16(int uint16,DataOutputStream stream) throws IOException {
        writeUInt8(uint16 >> 8, stream);
        writeUInt8(uint16, stream);
    }

public void writeUInt8(int uint8,DataOutputStream stream) throws IOException {
        stream.write(uint8 & 0xFF);
    }

要增加混乱,请写入文件,然后通过网络传输,这将为我发送正确的值!因此,当outputstream指向本地文件时,它将写入正确的值,但是当outputstream指向ByteArrayOutputStream时,则写入的长值是错误的.

To add to the confusion writing to a file and then transporting it over the network sends me the correct value! So when outputstream points to a local file then it writes the correct values but when outputstream points to a ByteArrayOutputStream then the long value written is wrong.

推荐答案

只需使用DataOutput/InputStream.

Just use DataOutput/InputStream.

要编写,请将您的long强制转换为int

To write, cast your long to int

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

读取时,使用readInt,分配给long并屏蔽前32位以获取无符号值.

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;
}

编辑

从您的问题来看,您似乎对基本类型的Java转换和升级感到困惑.

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

阅读有关转化和促销的Java规范的这一部分: http ://java.sun.com/docs/books/jls/third_edition/html/conversions.html

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

这篇关于通过网络写入4字节的unsigned int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆