我在用 java 编写无符号 4 字节 int 时遇到问题。
在 64 位 MacOS 和 32 位 Linux (Ubuntu) 上,无论是在 java 中写入一个 long 值都会有不同的结果 或者 将 4 字节无符号整数写入网络有问题。
以下调用在我的本地 OSX 上完美运行
writeUInt32(999999,outputstream)
读回来给我 999999
然而,当应用程序部署到网络时,写入一个长值会产生一些其他随机数(我假设字节序已被切换?)并读取它会给我一些其他大数。
------------完整的方法栈如下----------------
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 时,写入的 long 值是错误的。
最佳答案
只需使用 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 转换和提升感到困惑。
阅读关于转换和促销的 Java 规范的这一部分:http://java.sun.com/docs/books/jls/third_edition/html/conversions.html
关于java - 通过网络写入 4 个字节的无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7830175/