在java中是否可以打包一个预计不是负数的整数&最终(不是溢出)变成简短的?
将“unsigned int”改成short 并返回。这可能吗?如果是的话该怎么办呢?
咕噜咕噜。我忘记了带符号的数字是如何实现的。这个问题没有意义。不管怎样,谢谢。我本来打算自己投反对票,你可以这样做。
"Unsigned int" into a short and back. Is this possible? How 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定我完全理解这个问题,但如果你确定你的 int 适合短整型(你的数字在 0 到 2^16 之间),你总是可以将你的 int 转换为短整型:
并获取无符号值:
int i2 = s & 0xFFFF;
System.out.println(i2);
s & 0xFFFF 会将 s 向上转换为 int,位掩码会将负数“转换”为其无符号值(某种意义上)。请记住,短变量中的 FFFF 是 -1,而不是 65536。
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:
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.
如果你的整数没有任何特定的特征,比如是某个东西的倍数,我认为你不能。
问题是包含在 int(通常是 32 位架构)中的信息不能包含在 Short 中。
正如您从
Short.MAX_VALUE
中看到的那样,最大值是 2^15 - 1,因为 Short 占用 16 位。因此您实际上会丢失精度,并且无法表达像 2²² 这样的整数。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²²..如果您想要无符号类型,可以使用 Javolution 库。
If you want unsigned types, you can use the Javolution library.