简体   繁体   中英

Why can't I convert signed int to unsigned long

I'm reading numeric data from a file in Java:

Data of one byte length represents an unsigned byte Data of two bytes length represents an unsigned short Data of four bytes length represents an unsigned int

But because Java 7 doesn't have unsigned types, I need to use a short / integer to represent the whole range of byte values, an integer to represent a short value and I assume a long to represent an integer value.

But I'm having problems with representing the integer values

I have these three methods:

 public class Utils 
 { 
    public static int u(short n)
    {
        return n & 0xffff;
    }


    public static int u(byte n)
    {
        return n & 0xff;
    }

     public static long u(int n)
    {
        return n & 0xffffffff;
    }
}

and three test cases, but only the first two test cases work:

public void testByteToUnsignedIntConversion()
    {
        byte maxByte = (byte)0xff;
        int  maxNotConverted = maxByte;
        int  maxConverted    = Utils.u(maxByte);
        System.out.println(maxConverted + ":" + maxNotConverted);
        assertEquals(255,maxConverted);
    }

    public void testShortToUnsignedIntConversion()
    {
        short maxShort = (short)0xffff;
        int  maxNotConverted = maxShort;
        int  maxConverted    = Utils.u(maxShort);
        System.out.println(maxConverted + ":" + maxNotConverted);
        assertEquals(65535,maxConverted);
    }

    public void testIntToUnsignedLongConversion()
    {
        int maxInt = 0xffffffff;
        long  maxNotConverted = maxInt;
        long  maxConverted    = Utils.u(maxInt);
        System.out.println(maxConverted + ":" + maxNotConverted);
        assertEquals(4294967296l,maxConverted);
    }

What am I misunderstanding?

Guava不用自己动手,而是提供了用于无符号值的辅助方法UnsignedIntsUnsignedLongs等(有关更多信息,请参见其wiki ),并且Java 8中也有内置方法可以使用parseUnsignedIntdivideUnsigned

Bitwise and (&) deals with operands as integers unless you state otherwise. that's why it worked with byte and short since the methods return an integer. so since you want the result to be a long value to deal with it as unsigned value, you should and with the integer max value mask (ie 2^32-1 or 0xFFFFFFFF) and cast it long. Long constants should end with L in java, so just modify it to the following:

public static long u(int n)
{
    return n & 0xffffffffL;
}

if what you you need is make arithmetic operations on the unsigned values and it doesn't matter which version of java you use, I would suggest to use java 8 since it has methods in Long, Integer, Byte and Short classes to do such unsigned operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM