Unsigned short in Java

2020-01-26 06:37发布

How can I declare an unsigned short value in Java?

15条回答
2楼-- · 2020-01-26 07:26

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.

查看更多
Bombasti
3楼-- · 2020-01-26 07:26

Simple program to show why unsigned numbers are needed:

package shifttest;
public class ShiftTest{
    public static void main(String[] args){
        short test = -15000;
        System.out.format ("0x%04X 0x%04X 0x%04X 0x%04X 0x%04X\n",
            test, test>>1, test>>2, test>>3, test>>4);
    }
}

results:

0xC568 0xFFFFE2B4 0xFFFFF15A 0xFFFFF8AD 0xFFFFFC56

Now for those that are not system types:

JAVA does an arithmetic shift because the operand is signed, however, there are cases where a logical shift would be appropriate but JAVA (Sun in particular), deemed it unnecessary, too bad for us on their short sightedness. Shift, And, Or, and Exclusive Or are limited tools when all you have are signed longer numbers. This is a particular problem when interfacing to hardware devices that talk "REAL" computer bits that are 16 bits or more. "char" is not guaranteed to work (it is two bytes wide now) but in several eastern gif based languages such as Chinese, Korean, and Japanese, require at least 3 bytes. I am not acquainted with the number need for sandscript style languages. The number of bytes does not depend on the programmer rather the standards committee for JAVA. So basing char as 16 bits has a downstream risk. To safely implement unsigned shorts JAVA, as special class is the best solution based on the aforementioned ambiguities. The downside of the class is the inability of overloading the mathematical operations for this special class. Many of the contributors for this thread of accurately pointed out these issues but my contribution is a working code example and my experience with 3 byte gifs languages in C++ under Linux.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-26 07:29

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.

查看更多
不美不萌又怎样
5楼-- · 2020-01-26 07:32

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.

查看更多
倾城 Initia
6楼-- · 2020-01-26 07:33

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.

查看更多
何必那么认真
7楼-- · 2020-01-26 07:34
//вот метод для получения аналога unsigned short
    public static int getShortU(byte [] arr, int i )  throws Exception 
    {
       try
       {
           byte [] b = new byte[2]; 
           b[1] = arr[i];
           b[0] = arr[i+1];
           int k = ByteBuffer.wrap(b).getShort();
            //if this: 
           //int k = ((int)b[0] << 8) + ((int)b[1] << 0); 
           //65536 = 2**16
           if ( k <0) k = 65536+ k; 
        return k;
      }  
       catch(Throwable t)
      {
          throw  new Exception ("from getShort: i=" + i);
      }
    }
查看更多
登录 后发表回答