开发者

In java is it possible to pack a integer number that is expected not to be negative & be final (not overflow) into a short?

开发者 https://www.devze.com 2022-12-24 13:08 出处:网络
\"Unsigned int\" into a short and back. Is this possible? Ho开发者_开发技巧w to do it if so? Grrrr. I forgot how signed numbers are implemented. The question makes no sense. Thanks anyway. I was goin

"Unsigned int" into a short and back. Is this possible? Ho开发者_开发技巧w to do it if so?

Grrrr. I forgot how signed numbers are implemented. The question makes no sense. Thanks anyway. I was going to downvote myself, you can do it instead.


I'm not sure I fully understand the question but if you are sure that your int fit into a short (you number is between 0 and 2^16) you can always cast your int to a short:

int i = 65536;
short s = (short) i;

And to get the unsigned value back: int i2 = s & 0xFFFF; System.out.println(i2);

The s & 0xFFFF will upcast s to an int and the bit mask will "convert" the negative number to it's unsigned value (sort of). Remember that FFFF in a short variable -1 not 65536.


Sounds like you're hoping for a basic type that'll do the work for you, but I don't think one exists. On the other hand, I don't imagine it would be too difficult to create an object that does the work. Adjust as necessary to make it a short.

public class SpecialInt {
 int i = 0;

 public void set(int i) {
  if ( i < 0 ) throw new IllegalArgumentException("cannot be negative");
  this.i = i;
 }

 public void add(int j) {
  int t = i+j;
  if( t < i ) throw new IllegalArgumentException("overflow!");
  i = t;
 }

 public void sub(int j) {
  int t = i-j;
  if( t > i ) throw new IllegalArgumentException("overflow!");
  i = t;
 }

 public void mult(int j) {
  int mult_max = Integer.MAX_VALUE / i;
  if( j > mult_max ) throw new IllegalArgumentException("overflow!");
  i *= j;
 }
}


If your integer number doesn't have any specific characteristic like being a multiple of something I don't think you can.

The problem is that information contained into an int, that usually is 32 bit architecture cannot be contained into a short.

As you can see from Short.MAX_VALUE tha maximum value is 2^15 - 1, since a short occupies 16 bit.. so you actually lose precision and you can't express integers like 2²²..


If you want unsigned types, you can use the Javolution library.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号