2

Java does not support unsigned integer types and the easiest way to represent an unsigned integer in Java is using a larger integer type.
DataInput interface does provide methods for reading unsigned integer types - readUnsignedByte, which returns short and readUnsignedShort, which returns int.

Why doesn't this interface have a readUnsignedInt method that would return long? Is there any particular reason?

Clarification: I'm aware of Java 8 support for unsigned arithmetic. The question is not how to deal with this problem, but why the DataInput interface doesn't have such a method.

JeB
  • 11,653
  • 10
  • 58
  • 87

2 Answers2

2

I don't know why, but it's no longer a problem because there is now support for unsigned ints. You can do

long a = Integer.toUnsignedLong(r.readInt());
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • Yes, I'm aware of that. But the question is really not about dealing with the problem, but about this particular interface. Thanks for the response, anyways. – JeB Mar 24 '16 at 16:57
  • 3
    @binyan Fair enough - I realise it wasn't your question. You'd have to ask the language designers. Since this interface goes back to Java 1.0, there's only a very small number of people who will know. My guess is that they wanted the interface to have as few methods as possible, and you can do without this one. – Paul Boddington Mar 24 '16 at 17:02
1

DataInput/DataOutput has a method for each of the primitives and String.

unsigned int is not a primitive but you can do the following since it was added.

long a = dis.readInt() & 0xFFFF_FFFFL;

dos.writeInt((int) a);

Why this interface doesn't have a readUnsignedInt method that would return long?

I assume the original designers didn't think you need one or they would have added an unsigned int type.

Is there any particular reason?

There is so many things you could add (and in my library I have added because I think they are useful) but the designers seemed to believe less is more.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    I understand your point, but why then they did add the `readUnsignedByte` and `readUnsignedShort` methods? How is that different from `readUnsignedInt` from the point of necessity? It makes me think there is something more than just "less is better" approach. But I have no clue what the real reason could be... – JeB Mar 24 '16 at 20:33
  • 2
    @binyan fair point. It is inconsistent. I guess it's because `readUnsignedByte` and `Short` return an `int`. Though returning a `long` isn't exactly a leap. – Peter Lawrey Mar 24 '16 at 20:40