本文介绍了Java中的Unsigned Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现现有的网络协议,该协议大量使用Java不支持的无符号数据类型。我目前所做的是针对每种数据类型,选择下一个更大的数据类型,以便无符号数可以适合正区域,然后使用字节移位来获得所需的效果。因为这很容易出错,而且对于无符号长时间的向前我必须使用比扩展类型重得多的BigInteger,我想知道是否有更好的方法来实现这一点?

I'm trying to implement an existing network protocol which makes heavy use of Unsigned datatypes, which are not supported by Java. What I currently do is for each datatype, chose the next bigger one so that the unsigned number may fit into the positive region and then use byte shifting to get the desired effect. Since this is pretty error prone and for an unsigned long onward I have to use BigInteger which is a lot heavier than expanded types, I was wondering if there isn't a better way to achieve this?

推荐答案

根据您的操作,您可以将long视为64位值,将int视为32位值。大多数操作esp readInt / Long writeInt / Long通过忽略符号来工作。

Depending on what you are doing, you can just treat long as a 64-bit value and int as a 32-bit value. Most operations esp readInt/Long writeInt/Long work just the same by ignoring the signness.

你能给出你对这些数字进行操作的一个例子,也许我们可以建议如何在不扩展类型的情况下做同样的事情。

Can you give an example of operation you perform on these numbers and perhaps we can suggest how would do the same thing without having to expand the type.

例如,++, - ,+, - ,*,==,!=,<<无论signess如何,所有工作都相同(即给出相同的答案)。 for >>你可以替换>>>

For example, ++, --, +, -, *, ==, !=, << all work the same regardless of signess (i.e. give the same answer). for >> you can substitue >>>

这是/,%,>,> =,<,< =和打印函数,它们采用有符号值,但你应该可以解决这些问题(如果你使用这些)。

It is the /, %, >, >=, <, <= and printing functions which assume signed values, but you should be able to work around these (if you use these).

例如

long unsignedA =
long unsignedB =
boolean greater = unsignedA + Long.MIN_VALUE > unsignedB + Long.MIN_VALUE

编辑:为什么这样做?部分原因是java没有溢出/下溢异常。

Why does this work? Partly because java doesn't have overflow/underflow exceptions.

例如

byte unsignedA = 0;
unsignedA--;
// unsignedA == FF, is this -1 or 255? Java assumes the former but you assume the later

byte unsignedB = unsignedA * unsignedA;
// unsignedB is -1 * -1 = 1 or (byte) (255*255) = (byte) 65525 = 1.

这篇关于Java中的Unsigned Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:36