How to Parse Negative Long in Hex in Java

后端 未结 3 995
清歌不尽
清歌不尽 2020-12-09 05:38

We have a J2ME application that needs to read hex numbers. The application is already too big for some phones so We try not to include any other codec or write our own funct

相关标签:
3条回答
  • 2020-12-09 05:48

    Your problem is that parseLong() does not handle two's complement - it expects the sign to be present in the form of a '-'.

    If you're developing for the CDC profile, you can simple use

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

    But the CLDC profile doesn't have that class. 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():

    long l = Long.parseUnsignedLong("FFFFFFFFFFFFFFFF", 16);
    
    0 讨论(0)
  • 2020-12-09 05:51

    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 (i.e. subtract 8 from that digit), parse the result, and add the parsed value to the lower bound of a signed long? (Essentially just doing the 2's complement yourself.)

    0 讨论(0)
  • 2020-12-09 05:55

    Parse it in chunks.

        long l = (Long.parseLong("FFFFFFFFF",16)<<32) | Long.parseLong("FFFFFFFF",16);
    
    0 讨论(0)
提交回复
热议问题