简体   繁体   English

如何在Java中以十六进制解析负长

[英]How to Parse Negative Long in Hex in Java

We have a J2ME application that needs to read hex numbers. 我们有一个J2ME应用程序,需要读取十六进制数字。 The application is already too big for some phones so We try not to include any other codec or write our own function to do this. 对于某些手机来说,该应用程序已经太大了,因此我们尝试不包括任何其他编解码器或编写我们自己的函数来执行此操作。

All the numbers are 64-bit signed integers in hex, when we use Long.ParseLong(hex, 16), it handles positive numbers correctly but it throws exception on negative numbers, 所有数字都是十六进制的64位有符号整数,当我们使用Long.ParseLong(hex,16)时,它可以正确处理正数,但会在负数上引发异常,

    long l = Long.parseLong("FFFFFFFFFFFFFFFF", 16);

How can we get -1 from that hex string using classes provided in Java itself? 我们如何使用Java本身提供的类从十六进制字符串中获得-1?

Some people may suggest we should write our hex as -1 as Java expected. 有人可能建议我们应该像Java预期的那样将十六进制写为-1。 Sorry, the format is fixed by the protocol and we can't change it. 抱歉,该格式是由协议确定的,我们无法更改。

Your problem is that parseLong() does not handle two's complement - it expects the sign to be present in the form of a '-'. 您的问题是parseLong()无法处理二进制补码-它希望符号以“-”形式出现。

If you're developing for the CDC profile, you can simple use 如果您正在开发CDC配置文件,则可以轻松使用

long l = new BigInteger("FFFFFFFFFFFFFFFF", 16).longValue()

But the CLDC profile doesn't have that class. 但是CLDC配置文件没有该类。 There, the easiest way to do what you need is probably to split up the long, parse it in two halves and recombine them. 在那里,执行所需操作的最简单方法可能是将长整型分割成两半,然后重新组合。 This works: 这有效:

long msb = Long.parseLong("FFFFFFFF", 16);
long lsb = Long.parseLong("FFFFFFFF", 16);
long result = msb<<32 | lsb;

UPDATE 更新

As of Java 8, you can use parseUnsignedLong() : 从Java 8开始,您可以使用parseUnsignedLong()

long l = Long.parseUnsignedLong("FFFFFFFFFFFFFFFF", 16);

大量解析它。

    long l = (Long.parseLong("FFFFFFFFF",16)<<32) | Long.parseLong("FFFFFFFF",16);

Worse case scenario, you could check to see if the string is 16 characters that begins with an 8-F, and if so, change that to the equivalent character w/o the most significant bit set (ie subtract 8 from that digit), parse the result, and add the parsed value to the lower bound of a signed long? 更糟糕的情况是,您可以检查字符串是否为以8-F开头的16个字符,如果是,则将其更改为不包含最高有效位集的等效字符(即从该数字中减去8),解析结果,并将解析后的值添加到有符号long的下限? (Essentially just doing the 2's complement yourself.) (基本上只是自己做2的补码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM