2

I have a hexadecimal number in a String which is too large to convert to int and long and want to add the value of another hexadecimal number. So let's say I have this number:

String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";

And want to add:

int hex2 = 0x1;  or  String hex2 = "0x1";

I know this question has been asked allready How to subtract or add two hexadecimal value in java but the answers don't work for me because they all involve conversion to int.

2
  • 3
    So convert them to a BigInteger. docs.oracle.com/javase/8/docs/api/java/math/… Commented Jan 5, 2020 at 16:41
  • 1
    If you don't convert the String to an integral type, then adding those two String(s) will give you "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d910x1" - which I bet you don't want. Commented Jan 5, 2020 at 16:42

2 Answers 2

2

You can do it as follows:

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
        String hex2 = "0x1";
        System.out.println(
                "In decimal: " + new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)));
        System.out.println("In hexdecimal: "
                + new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)).toString(16));
    }
}

Output:

In decimal: 109684320921920394042076832992416841330182602685967688614501993994243850001810
In hexdecimal: f27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d92
Sign up to request clarification or add additional context in comments.

Comments

-1

Change your code to:

String hex1="0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
int hex2=0x1;
string hex2="0x1";

You need "" for entering a value for string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.