Add integer in 27 char hex string in java - java

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

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

Use BigInteger in Java
That will satisfy your requirements.
Visit the following tutorial to learn BigInteger in Java : TutorialPoint

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.

BigInteger b = new BigInteger("FF", 16);
BigInteger bPlus1 = b.plus(1);
String hex = bPlus1.toString(16); // 0x100

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

Related

How to divide a BigInteger by integer?

(EDIT: Before more people downvote, I did look at the Javadoc beforehand but since I'm a beginner I wasn't sure where in the document to look. See my response to Jim G, which is posted below. I understand that this question is maybe viewed as too basic. But I think it has some value for other beginners in my situation. So please, consider the full situation from a beginner's perspective before downvoting.)
I want to divide a BigInteger by a regular integer (i.e. int) but I don't know how to do this. I did a quick search on Google and on Stack Exchange but didn't find any answers.
So, how can I divide a BigInteger by an int? And while we're at it, how can I add/subtract BigInts to ints, compare BigInts to ints, et cetera?
Just use BigInteger.valueOf(long) factory method. An int can be implicitly "widened" to be long... This is always the case when going from smaller to large, e.g. byte => short, short => int, int => long.
BigInteger bigInt = BigInteger.valueOf(12);
int regularInt = 6;
BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt));
System.out.println(result); // => 2
Convert the Integer to BigInteger and than divide both BigInteger, as following:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
//convert the integer to BigInteger.
BigInteger converted = new BigInteger(Integer.toString(x));
//now you can divide, add, subtract etc.
BigInteger result = b.divide(converted); //but this will give you Integer values.
System.out.println(result);
result = b.add(converted);
System.out.println(result);
Above division will give you Integer values of divisions, to get exact values, use BigDecimal.
EDIT:
To remove two intermediate variables converted and result in above code:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
System.out.println(b.divide(new BigInteger(Integer.toString(x))));
OR
Scanner in = new Scanner(System.in);
System.out.println(BigInteger.valueOf((in.nextInt())).divide(new BigInteger(Integer.toString(in.nextInt()))));

Convert hex string into long 17digits java

I am trying to convert "0x6042607b1ba01d8dl" into a long.
I have tried:
long value = new BigInteger("0x6042607b1ba01d8dl", 16).longValue();
long value = new BigInteger("0x6042607b1ba01d8dl", 32).longValue();
long value = Long.decode("0x6042607b1ba01d8dl");
Long.parseLong("0x6042607b1ba01d8dl");
Note: The Hex number "0x6042607b1ba01d8dl" has 17 numbers
From the javadoc for the BigInteger(String,int) constructor:
The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix.
So you just need to remove the 0x from your string:
long value = new BigInteger("6042607b1ba01d8d", 16).longValue();
The BigInteger constructor does not understand your 0x prefix.
Use e.g.
long value = new BigInteger("6042607b1ba01d8d", 16).longValue();
Or:
String number = "0x6042607b1ba01d8d";
long value = new BigInteger(number.subString(2), 16).longValue();
You can also use Long.decode(), which does accept a 0x prefix for decoding hex.
You can try this:
long value = Long.parseLong("6042607b1ba01d8d", 16);
Long.parseLong can sometimes fail for unsigned longs, so, the BigInteger approaches are better.
As said by the above answers in code form:
String bigHexNumber = "0x6042607b1ba01d8d";
if(bigHexNumber.subString(0, 1).equals("0x") {
bigHexNumber = bigHexNumber.subString(2);
}
long hexInLongForm = new BigInteger(bigHexNumber, 16).longValue();

Java parsing long from string

I'm currently trying to parse some long values stored as Strings in java, the problem I have is this:
String test = "fffff8000261e000"
long number = Long.parseLong(test, 16);
This throws a NumberFormatException:
java.lang.NumberFormatException: For input string: "fffff8000261e000"
However, if I knock the first 'f' off the string, it parses it fine.
I'm guessing this is because the number is large and what I'd normally do is put an 'L' on the end of the long to fix that problem. I can't however work out the best way of doing that when parsing a long from a string.
Can anyone offer any advice?
Thanks
There's two different ways of answering your question, depending on exactly what sort of behavior you're really looking for.
Answer #1: As other people have pointed out, your string (interpreted as a positive hexadecimal integer) is too big for the Java long type. So if you really need (positive) integers that big, then you'll need to use a different type, perhaps java.math.BigInteger, which also has a constructor taking a String and a radix.
Answer #2: I wonder, though, if your string represents the "raw" bytes of the long. In your example it would represent a negative number. If that's the case, then Java's built-in long parser doesn't handle values where the high bit is set (i.e. where the first digit of a 16 digit string is greater than 7).
If you're in case #2, then here is one (pretty inefficient) way of handling it:
String test = "fffff8000261e000";
long number = new java.math.BigInteger(test, 16).longValue();
which produces the value -8796053053440. (If your string is more than 16 hex digits long, it would silently drop any higher bits.)
If efficiency is a concern, you could write your own bit-twiddling routine that takes the hex digits off the end of the string two at a time, perhaps building a byte array, then converting to long. Some similar code is here:
How to convert a Java Long to byte[] for Cassandra?
The primitive long variable can hold values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 inclusive.
The calculation shows that fffff8000261e000 hexademical is 18,446,735,277,656,498,176 decimal, which is obviously out of bounds. Instead, fffff8000261e000 hexademical is 1,152,912,708,553,793,536 decimal, which is as obviously within bounds.
As everybody here proposed, use BigInteger to account for such cases. For example, BigInteger bi = new BigInteger("fffff8000261e000", 16); will solve your problem. Also, new java.math.BigInteger("fffff8000261e000", 16).toString() will yield 18446735277656498176 exactly.
The number you are parsing is too large to fit in a java Long. Adding an L wouldn't help. If Long had been an unsigned data type, it would have fit.
One way to cope is to divide the string in two parts and then use bit shift when adding them together:
String s= "fffff8000261e000";
long number;
long n1, n2;
if (s.length() < 16) {
number = Long.parseLong(s, 16);
}
else {
String s1 = s.substring(0, 1);
String s2 = s.substring(1, s.length());
n1=Long.parseLong(s1, 16) << (4 * s2.length());
n2= Long.parseLong(s2, 16);
number = (Long.parseLong(s1, 16) << (4 * s2.length())) + Long.parseLong(s2, 16);
System.out.println( Long.toHexString(n1));
System.out.println( Long.toHexString(n2));
System.out.println( Long.toHexString(number));
}
Note:
If the number is bigger than Long.MAX_VALUE the resulting long will be a negative value, but the bit pattern will match the input.

10bit binary number from a string to a byte

Currently I have a 8 bit binary string and I want to shift it left and get a 10bit binary number from it.
(ie 0111001010)
String[] channels = datArray.get(n).split(" ");
byte[] RI = channels[m+1].getBytes();
String s = (Integer.toBinaryString(Integer.parseInt(channels[m+1])));
Example Values:
RI is equal to: [B#4223b758
S is equal to: 1100101
Any help is much appreciated.
Wouldn't this work for you:
String input = "1100101";
int value = Integer.parseInt(input, 2) << 1;
System.out.println(Integer.toBinaryString(value));
Returns:
11001010
Parsed binary string and shifted left (one digit).
The two things that it looks like you are missing from your approach are the ability to specify a radix when parsing a String representing a binary numeral, and the left shift operator.
If you wanted the leading zeros I was surprised to see that there is no built in way to accomplish this, and the current wisdom is this is the optimal way (taken from this discussion)
System.out.println(String.format("%10s", Integer.toBinaryString(value)).replace(' ', '0'));
Which for the example value given would return this:
0011001010
You can use following:
BigInteger i = new BigInteger("00000011" + "00", 2);
int x = i.intValue();
Where "00000011" is your string representation of 8 bit number. The "00" simulates the left shifting..

Java Hexa Complement

How does one obtain the complementary hexadecimal value for a given input ?
This could be a bit more generic, i.e. having an array of X possible values, how do you convert a random array like arr[x] --> arr[arr.length - arr.indexOf(x)].
Please ignore the syntax.
The following code snippet will find 16 complement of hexadecimal number:
BigInteger subtrahend = new BigInteger("2D", 16);
// input, you can take input from user and use after validation
char[] array = new char[subtrahend.toString(16).length()];
// construct a character array of the given length
Arrays.fill(array, 'F');
// fill the array by F, look at the first source there the FF is subtracted by 2D
BigInteger minuend = new BigInteger(new String(array), 16);
// construct FFF... Biginteger of that length
BigInteger difference = minuend.subtract(subtrahend);
// calculate minus
BigInteger result = difference.add(BigInteger.ONE);
// add one to it
System.out.println(result.toString(16));
// print it in hex format
Hope this will help you. Thank you.
Source:
Binary and Hexadecimal Arithmetic
Digital Principles and Logic Design
First find the 15's complement of the given input by subtracting it from the number FF... which is of the same length of the input. Then add 1 to it.

Categories

Resources