简体   繁体   中英

How to remove trailing zeros from hexadecimal string?

I have hexadecimal string like 02011A020A060AFF4C0010055D18C66C96000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

I want to remove all the trailing zeros and convert string to decimal.

I am trying to convert string using

long = Integer.parseInt(it, 16)

but getting NumberFormatException for mentioned string.

Please suggest.

To replace trailing zeroes as per the question

   String s = "02011A020A060AFF4C0010055D18C66C96000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
   String t = s.replaceFirst("(00)*$", "");

The result is still not representable as int or long , though. That is a simple fact.

You can use the BigInteger class.

Your string represents a very big integer that can not be accommodated into an int type of variable. You can parse it to a decimal integer using BigInteger .

Demo:

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger num = new BigInteger(
                "02011A020A060AFF4C0010055D18C66C96000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                16);
        System.out.println(num);
    }
}

Output:

1601774156032550143629384364472675906890742343243921647127483666720143286838483191778518780074715465142869671834006975796514903403440608079859679232

However, if you are just interested to know how to get rid of the trailing zeros from your string, you can replace the regex , 0+$ with "" . However, note that it will change the value of the number eg 9 (without a trailing zero) is not equal to 90 (with a trailing zero).

Demo:

public class Main {
    public static void main(String[] args) {
        String num = "02011A020A060AFF4C0010055D18C66C96000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
        num = num.replaceAll("0+$", "");
        System.out.println(num);
    }
}

Output:

02011A020A060AFF4C0010055D18C66C96

Explanation of the regex:

  • 0+ : One or more zero(s)
  • $ : asserts position at the end of a line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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