2

I have a hex String 240300000800000000000000004. I want to add integer in this hex code and get back hex code in java.

As java does not support this muck length of value, so how do we do this?

Thanks Abhishek

2
  • Maybe , he focussed more on value rather adding 0x Commented Jul 19, 2013 at 10:13
  • The words "a hex String" make it hex. Commented Jul 19, 2013 at 14:19

5 Answers 5

7
String str = "240300000800000000000000004";
BigInteger bi = new BigInteger(str, 16);
Integer ii = 10; // Integer to add
bi = bi.add(new BigInteger(ii.toString()));
System.out.println(bi.toString(16)); // 24030000080000000000000000e
Sign up to request clarification or add additional context in comments.

4 Comments

I didn't downvote , I believe sharing the code triggered the downvote perhaps !
@TheNewIdiot: When code is not shared a link is provided then folks complain that better to provide code snippet as links can be broken and now they don't like direct help either.... what to say.
I believe this should be marked as the answer. As this provides the complete solution instead of a tutorial
Perhaps the downvoter does not understand what a 'radix' is? Or how one might create an BigInteger from a hex string by specifying the base 16 to convert from.
7

Use BigInteger in Java

That will satisfy your requirements.

Visit the following tutorial to learn BigInteger in Java : TutorialPoint

Comments

3

The easiest solution is the already posted one of using BigInteger. However, you can also process the addition in chunks such that the result and any carry will fit in a long. Start at the right hand end with carry-in zero. Take a group of up to 15 hex digits, convert to long, do the addition including any carry-in from the addition to the right of this chunk, store the 15 least significant digits of the result into the output string, and remember the most significant digit to use as the carry-out from this addition, the carry-in to the next addition to the left.

2 Comments

@TimBender Yes. Replace the 15 byte chunk with a decimal digit, and it's elementary school addition. Replace it with a single bit, and it's the naive way of using a full adder to build a multi-bit adder.
Yes, and to that end, one could also write a hex adder which will carry a 0-F value up each digit.
1
BigInteger b = new BigInteger("FF", 16);
BigInteger bPlus1 = b.plus(1);
String hex = bPlus1.toString(16); // 0x100

Comments

0
BigInteger bigint = new BigInteger("240300000800000000000000004" ,16);
    System.out.println(bigint);
    BigInteger s = new BigInteger("8");
    bigint = bigint.add(s);
    System.out.println(bigint);

1 Comment

Anybody has idea , how to convert a BigInteger into a HexaDeciaml value.

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.