开发者

Why no readUnsignedInt in RandomAccessFile class?

I just found there is no readUnsignedInt() method in the RandomAccessFile class. Why? Is there any workaround to read an unsigned int out from the file?

Edit:

I want to read an unsigned int from file and put it into a long space.

Edit2:

Cannot use readLong(). it will read 8 bytes not 4 bytes. the data in the file have unsigned ints in 4 bytes range.

Edit3:

Found answer here: http://www.petefreitag.com/item/183.cfm

Edit4:

how about if the data file is little-endian? we need to bi开发者_运维百科ts swap first?


I'd do it like this:

long l = file.readInt() & 0xFFFFFFFFL;

The bit operation is necessary because the upcast will extend a negative sign.


Concerning the endianness. To the best of my knowledge all I/O in Java is done in big endian fashion. Of course, often it doesn't matter (byte arrays, UTF-8 encoding, etc. are not affected by endianness) but many methods of DataInput are. If your number is stored in little endian, you have to convert it yourself. The only facility in standard Java I know of that allows configuration of endianness is ByteBuffer via the order() method but then you open the gate to NIO and I don't have a lot of experience with that.


Edited to remove readLong():

You could use readFully(byte[] b, int off, int len) and then convert to Long with the methods here: How to convert a byte array to its numeric value (Java)?


Because there is no unsigned int type in java? Why not readLong() ? You can readLong and then take first 32 bits.

Edit You can try

long value = Long.parseLong(Integer.toHexString(file.readInt()), 16);


Depending on what you are doing with the int, you may not need to turn it into a long. You just need to be aware of the operations you are performing. After all its just 32-bits and you can treat it as signed or unsigned as you wish.

If you want to play with the ByteOrder, the simplest thing to do may be to use ByteBuffer which allows you to set a byte order. If your file is less than 2 GB, you can map the entire file into memory and access the ByteBuffer randomly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜