0

I have this function:

public static final int UNSIGN(short b){

    return (b & 0xFFFF);
}

The intent here is to use the value in 'b' as if it were positive, by this I mean as if it were an unsigned int, capable of holding 65536 values. However, it doesn't work. For example:

If 'b == -122' the function returns '65414'.

I also tried this way:

public static final int UNSIGN(short b){

    return (b & 0xFF);
}

But that would return me '48' if 'b == 304'.

I'm really lost here, hope someone can help out.

4

1 回答 1

2

The intent here is to use the value in 'b' as if it were positive.

Do you mean you want to find the absolute value of b? That would be Math.abs.

But your code is treating b as if it were an unsigned short. When b is -122, the bits will be

1111111110000110

... which is 65414 when viewed as an unsigned value.

(122 is 0000000001111010, so to negate it you reduce the value by 1 and flip all the bits.)

于 2013-01-27T21:21:22.263 回答