Java read unsigned int, store, and write it back

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

I need to read an unsigned int from a quicktime file, and write it back to another quicktime file.

Currently I read the unsigned int into a Long but while writing it back I never managed to write the exact number back in 4 bytes as unsigned int. The long has the correct value that I need to write back. (eg 3289763894 or 370500) I am unable to even read the write a number smaller then Integer.MAX_VALUE (eg 2997).

I am using the following methods to write the value back

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

Any help would be appreciated.

回答1:

Just write your long casted to int. I checked:

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

Output is

4280287229 vs -14680067 255 31 255 253 1048573 vs 1048573 0 15 255 253
as expected


回答2:

If you only want to read, store and rewrite it, then you can just use int. More general: as long as you do not interpret the bits you can just read, store and write them without caring about the intended interpretation of the bits.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!