1

I'm working with a third party server that takes ints as an input argument. However, when query the value I've written again, it seems to use the leftmost bit of the number as sign.. so 1000...0 (16 bits) would be returned as -32768, 11000...0 would be -16384, etc.

Given that Java doesn't know uints, I'm looking for an effective way to turn my negative number into the right positive number (the first one being 2^15, the second one being 2^15 + 2^24, and so on).

John
  • 577
  • 4
  • 20
user3566056
  • 224
  • 1
  • 12
  • Unclear what you are asking but maybe BigDecimal is what you are looking for? – Stefan Nov 05 '18 at 15:37
  • What type of variable do you have as the input? Is it a **String**? – Little Santi Nov 05 '18 at 15:38
  • 1
    Java 8 introduced unsigned int support [How to use the unsigned Integer in Java 8 and Java 9?](https://stackoverflow.com/q/25556017/995714) – phuclv Nov 05 '18 at 15:41
  • the lib I'm using returns me ints (or int array to be exact). Now much I can do about that. @Stefan: When I send 2^15, I get back -32768, when I send 2^15 + 2^14 I get back -16384. etc – user3566056 Nov 05 '18 at 15:42
  • @phuclv: I realize that.. but in my case I get ints back... that the other side mangled. I need to covert them back to actual values. Try putting -32768 into Integer.parseUnsignedInt... you'll get a NumberFormatException – user3566056 Nov 05 '18 at 15:43
  • what do you mean by "get back"? If you print that binary pattern as a signed type then obviously 0xFFFF8000 will become -32768. You must print it as unsigned. However it seems there's also the problem on the otherside, since it treats the value as short and not int – phuclv Nov 05 '18 at 15:47
  • Is "2^15 + 2^24" a typo? Because 2^24 is a lot bigger than 16384 (and you refer to 2^14 in your comments, so I suspect that's what you mean). – jsheeran Nov 05 '18 at 15:49
  • yeah you're right, I meant 2^15 + 2^14. and I got my own solution now.. adding 2^16 when the value is negative returns the proper value again. – user3566056 Nov 05 '18 at 15:58
  • 1
    But, if the lib you are using returns `int` values, how come do you get a -32768? – Little Santi Nov 05 '18 at 16:30
  • For unsigned 32 bit values you can use a `long l = x & 0xFFFFFFFFL;` – Peter Lawrey Nov 05 '18 at 18:29
  • For unsigned 16 values, just use int. `x &= 0xFFFF;` – Peter Lawrey Nov 05 '18 at 18:30

1 Answers1

2

For unsigned 16 bit values you can mask out the high bits

x &= 0xFFFF;

For unsigned 32 bit values, you can use a long

long l = x & 0xFFFFFFFFL;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130