【问题标题】:Java read unsigned int, store, and write it backJava 读取 unsigned int,存储并写回
【发布时间】:2011-11-22 15:52:08
【问题描述】:

我需要从一个 quicktime 文件中读取一个 unsigned int,然后将它写回另一个 quicktime 文件。

目前我将 unsigned int 读入 Long,但在写回它时,我从未设法将确切的数字以 4 个字节写回为 unsigned int。 long 具有我需要写回的正确值。 (例如 3289763894 或 370500) 我什至无法读取小于 Integer.MAX_VALUE 的数字(例如 2997)。

我正在使用以下方法将值写回

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

任何帮助将不胜感激。

【问题讨论】:

  • 在java中没有unsigned int这样的东西。而 long 有 8 个字节。
  • 因为 long 是我们得到的最接近无符号整数的东西。

标签: java types unsigned-integer


【解决方案1】:

如果你只想读取、存储和重写它,那么你可以使用 int。 更一般:只要您不解释位,您就可以读取、存储和写入它们而无需关心位的预期解释

【讨论】:

    【解决方案2】:

    只需将您的 long 转换为 int。我检查了:

    
    PipedOutputStream pipeOut = new PipedOutputStream ();
    PipedInputStream pipeIn = new PipedInputStream (pipeOut);
    DataOutputStream os = new DataOutputStream (pipeOut);
    
    long uInt = 0xff1ffffdL;
    
    System.out.println ("" + uInt + " vs " + ((int) uInt));
    os.writeInt ((int) uInt);
    for (int i = 0; i < 4; i++) System.out.println (pipeIn.read ());
    
    uInt = 0x000ffffdL;
    System.out.println ("" + uInt + " vs " + ((int) uInt));
    os.writeInt ((int) uInt);
    for (int i = 0; i < 4; i++) System.out.println (pipeIn.read ());

    输出是

    4280287229 与 -14680067
    255
    31
    255
    253
    1048573 与 1048573
    0
    15
    255
    253
    符合预期

    【讨论】:

    • 由于 network/quicktime int 的容量比 java int 所能容纳的容量大,一些值的 int 会溢出
    • 您无法将大于 2^32 - 1 的值放入 4 个字节中。并且提供的代码对于小于 2^32 的任何数字都可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多