Unsigned short in Java

105,103

Solution 1

You can't, really. Java doesn't have any unsigned data types, except char.

Admittedly you could use char - it's a 16-bit unsigned type - but that would be horrible in my view, as char is clearly meant to be for text: when code uses char, I expect it to be using it for UTF-16 code units representing text that's interesting to the program, not arbitrary unsigned 16-bit integers with no relationship to text.

Solution 2

If you really need a value with exactly 16 bits:

Solution 1: Use the available signed short and stop worrying about the sign, unless you need to do comparison (<, <=, >, >=) or division (/, %, >>) operations. See this answer for how to handle signed numbers as if they were unsigned.

Solution 2 (where solution 1 doesn't apply): Use the lower 16 bits of int and remove the higher bits with & 0xffff where necessary.

Solution 3

This is a really stale thread, but for the benefit of anyone coming after. The char is a numeric type. It supports all of the mathematical operators, bit operations, etc. It is an unsigned 16.

We process signals recorded by custom embedded hardware so we handle a lot of unsigned 16 from the A-D's. We have been using chars all over the place for years and have never had any problems.

Solution 4

You can use a char, as it is an unsigned 16 bit value (though technically it is a unicode character so could potnetially change to be a 24 bit value in the future)... the other alternative is to use an int and make sure it is within range.

Don't use a char - use an int :-)

And here is a link discussing Java and the lack of unsigned.

Solution 5

From DataInputStream.java

public final int readUnsignedShort() throws IOException {
    int ch1 = in.read();
    int ch2 = in.read();
    if ((ch1 | ch2) < 0)
        throw new EOFException();
    return (ch1 << 8) + (ch2 << 0);
}
Share:
105,103
maiky
Author by

maiky

Updated on July 05, 2022

Comments

  • maiky
    maiky almost 2 years

    How can I declare an unsigned short value in Java?

  • TofuBeer
    TofuBeer over 14 years
    byte is 8 bit, short is 16 bit... don't think byte will work :-)
  • Ken
    Ken over 14 years
    char is defined to be 16 bits, not a Unicode character (whatever that means), always and forever. If char changed to 24 bits, it would no longer be Java.
  • TofuBeer
    TofuBeer over 14 years
    I don't think it'll ever change either. The reason why 16 bits is to support unicode (from the JLS: "The Java platform tracks the Unicode specification as it evolves." and "The Unicode standard was originally designed as a fixed-width 16-bit character encoding") and from java.lang.Character: "The methods that only accept a char value cannot support supplementary characters" - so origianlly char was 16 bit because that was how wide unicode was. Now unicode is larger and char can no longer represent all unicode characters.
  • maiky
    maiky over 14 years
    i would like to build a multi-dimensional array with for example 10000*10000 entries of short numbers... thats why i thought of unsigned shorts, for allocating less memory
  • CBFraser
    CBFraser over 14 years
    Thanks for the correction, TofuBeer. Too quick on the draw, I guess.
  • CBFraser
    CBFraser over 14 years
    Makes sense, @maiky. Also, if you're worried about memory, you could probably lift the tricks from sparse matrices if you anticipate a lot of entries in your array will be zero.
  • tchrist
    tchrist almost 13 years
    @Jon: There seems to be no way in Java to have a normal machine‐level byte, meaning an 8‑bit location that can hold values [0–255] instead of [ −128 – +127 ]. I can’t believe they make us use signed bytes, when all you have to do in C is say unsigned char. Once you start down the road of signed datatypes only, it screws up all your unsigned bitmaps. Really quite unpleasant. The Java designers thought they were simplifying things to make them less error‐prone, but once again all they managed to do was make them a lot harder and more error‐prone than before. There’s a lot of that in Java.
  • ninjalj
    ninjalj almost 13 years
    @Jon: OTOH, since Java's char is unusable for Unicode codepoints, you can just as well use it for unsigned shorts: it won't be any more horrible than any existing code using char when they really should use int.
  • 9point6
    9point6 about 12 years
    Byte in java is also signed for some strange reason.
  • CITBL
    CITBL over 10 years
    You can use, System.out.format ("0x%04X 0x%04X 0x%04X 0x%04X 0x%04X\n", test, test & 0xffff >> 1, test & 0xffff >> 2, test & 0xffff >> 3, test & 0xffff >> 4);. This will give you an unsigned shift of short. However this adds 1 operation (bitwise &) to each shit.
  • Pacerier
    Pacerier almost 10 years
    @ninjalj, Oh where are you typedef?
  • essa
    essa about 8 years
    sBuff.append( new Integer(iArray[i++] & 0xffff) + ","); thank you!
  • BeeOnRope
    BeeOnRope over 7 years
    @tchrist - well FWIW it's not really accurate to imply that the "machine level" byte is 0-255 and not -128-+127. Machine bytes are just that - 8 bits, and the interpretation of the value may depend on the instruction used. In many cases whether you mentally treat a byte as signed or unsigned actually makes no difference to the assembly (e.g., addition, subtraction, some multiplication, all bit operations). The signed interpretation shouldn't matter for most bitmap use - all the bitwise operators operate as expected. It's only really sign extension on conversion you need to watch out for.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 7 years
    What, exactly, makes char horrible? This is FUD rather than help.
  • Jon Skeet
    Jon Skeet almost 7 years
    @AleksandrDubinsky: There's nothing wrong with char as a type - but using it as an unsigned 16 bit integer rather than text is an abuse of the type, IMO. When I see char in code, I think "UTF-16 code unit", not "arbitrary 16-bit integer".
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 7 years
    Java has a logical right shift operator, >>>. Also, char will never change its size.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 7 years
    @JonSkeet It would be better to bring up concrete reasons other than style before throwing out words like "horrible." What would be helpful to future visitors is if you repeated the contents of this answer stackoverflow.com/questions/397867/… in order to explain how to use unsigned data types in Java. In Java 8, the class Integer exposed some of these techniques as methods toUnsignedLong, compareUnsigned, divideUnsigned, etc, however there is value in a full documentation especially since class Short did not expose these methods.
  • Jon Skeet
    Jon Skeet almost 7 years
    @AleksandrDubinsky: I've added my reasoning to the answer, but kept "horrible" in there as I believe it is horrible. I'm not going to start repeating the content of other answers in a nearly-8-year-old answer.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 7 years
    @JonSkeet This page, and this answer, gets a lot of views. Of course, you're under no obligation to help the community.
  • Jon Skeet
    Jon Skeet almost 7 years
    @AleksandrDubinsky: How very passive-aggressive of you. I think we're done here. If anyone wants to follow your link, they can see the content to the other answer there.
  • Jon Skeet
    Jon Skeet almost 7 years
    @AleksandrDubinsky: Flagged. I'm done here. The idea that I "only work for points" is offensive and blatantly not the case.
  • MyStackRunnethOver
    MyStackRunnethOver over 5 years
    Hey there, welcome to Stack Overflow. This answer may be correct, but it could be improved in a couple ways: 1.) it would help if you explained what's going on in the code. How does the code solve the OP's problem? and 2.) since this is a fairly old question, what does your answer add that the existing answers don't already have?