Gan*_*nan 4 java networking unsigned casting long-integer
我在java中编写无符号4字节int时遇到问题.
在java中写一个long值在64位MacOS和32位Linux(Ubuntu)上有不同的结果或者写入一个4字节的unsigned int有一个问题.
以下调用在我的本地OSX上完美运行
writeUInt32(999999,outputstream)
Run Code Online (Sandbox Code Playgroud)
读回来给我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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加到写入文件的混乱,然后通过网络传输它给我发送正确的值!因此,当输出流指向本地文件时,它会写入正确的值,但是当输出流指向ByteArrayOutputStream时,则写入的长值是错误的.
只需使用DataOutput/InputStream.
写作,投你long
的int
public void writeUInt32(
long uint32,
DataOutputStream stream
) throws IOException
{
stream.writeInt( (int) uint32 );
}
Run Code Online (Sandbox Code Playgroud)
在读取时,使用readInt,分配给long并屏蔽前32位以获得无符号值.
public long readUInt32(
DataInputStream stream
) throws IOException
{
long retVal = stream.readInt( );
return retVal & 0x00000000FFFFFFFFL;
}
Run Code Online (Sandbox Code Playgroud)
编辑
从您的问题来看,您似乎对Java转换和原始类型的促销感到困惑.
阅读关于转换和促销的Java规范的这一部分:http://java.sun.com/docs/books/jls/third_edition/html/conversions.html
归档时间: |
|
查看次数: |
4455 次 |
最近记录: |