我在用java写一个无符号的4字节int时遇到问题。
在java中写入长值在64位MacOS和32位Linux (Ubuntu)上有不同的结果,或者在网络中写入4字节无符号整数有问题。
下面的调用在我本地的OSX上运行得很好。
writeUInt32(999999,outputstream)再读一遍我会得到999999
但是,当应用程序部署到网络时,写入一个长值会导致一些其他的随机数(我假设endian已经被交换了?)读到它会给我一些其他的大数字。
-完整的方法堆栈如下
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时,则写入的长值是错误的。
发布于 2011-10-20 11:03:27
只需使用DataOutput/InputStream即可。
要编写代码,请将long转换为int
public void writeUInt32(
long uint32,
DataOutputStream stream
) throws IOException
{
stream.writeInt( (int) uint32 );
}在读取时,使用readInt,赋值给long,并屏蔽最高32位以获得无符号值。
public long readUInt32(
DataInputStream stream
) throws IOException
{
long retVal = stream.readInt( );
return retVal & 0x00000000FFFFFFFFL;
}编辑
从您的问题看,您似乎对基本类型的Java cast转换和提升感到困惑。
阅读Java Spec on Conversion and Promotions的这一节:http://java.sun.com/docs/books/jls/third_edition/html/conversions.html
https://stackoverflow.com/questions/7830175
复制相似问题