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.

1
  • -122 is not positive so what value did you expect the function to return? Commented Jan 27, 2013 at 21:22

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

9 Comments

ok I guess I did not explain myself very well. I do not want the absolute value, I want the positive value for the 16bits. basically I want the value as if it were unsigned short.
@sazr: And that's exactly what it's giving you. What value did you want it to give you for b == -122?
why do you expect that value?
Exactly. Furthermore, in your question you write that you expect some result for b=304. So apparently, you don't want bytes either. Maybe you should take a step back and think about what you actually want, because if Jon Skeet's answer isn't right, the question is wrong.
If the parameter is always in [0;255], you have already given the correct answer in your question: return (b & 0xFF);. Just make sure you never call it with something else. (Also, if your question is hard to explain, what kind of answers do you expect when you give almost no explanation at all?)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.