hex string to decimal conversion [duplicate] - java

This question already has answers here:
Java Integer parseInt error
(4 answers)
Closed 6 years ago.
I need to convert the string of hex to decimal in java..
My hex value is "00000156A56BE980".
My required output is 1471654128000
I have done the following in java,
public static void main (String args [])
{
String hexValue = " 00000156A56BE980 ";
Integer result = Integer.parseInt(hexValue, 16);
System.out.println(result);
}
but I am getting the following error,
Number format Exception for input string "00000156A56BE980"
I have tried by giving long also the same error coming.. For other hex value it's coming but when we give hex string of larger value it shows the error.
How can we convert this number to decimal?
Can anyone solve this issue for me?

Try it like so
import java.math.*;
class Main {
public static void main (String args [])
{
String hexValue = "00000156A56BE980";
BigInteger result = new BigInteger(hexValue, 16);
System.out.println(result);
}
}
See also this repl.it
The problem is probably because your value does not fit within the value range (-231 to 232-1) of Integer - see the docs

The number is too large for a 32-bit int
Try using a long instead.
public static void main(String[] args) {
String hexValue = "00000156A56BE980";
long result = Long.parseLong(hexValue, 16);
System.out.println(result);
}
Note: you can't have spaces in a number. You can call .trim() to remove them.

2 thing in order the code can work:
remove spaces trimming the String
the result doenst fit in an integer so use either Long or BigInteger instead
public static void main(String[] args) {
String hexValue = " 00000156A56BE980 ";
long result = Long.parseLong(hexValue.trim(), 16);
System.out.println(result);
}

The number is too big for integer (> 2^32).
(The value represented by the string is not a value of type int.)
Take a look here

Related

How can I add two Strings containing hexadecimal-numbers without converting them to int?

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.
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
Change your code to:
String hex1="0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
int hex2=0x1;
string hex2="0x1";
You need "" for entering a value for string.

error while parsing an int from a char in String

import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.

Java format integer limiting width by truncating to the right

I know I could use String.substring or write some extra code, but is there a simple way to achieve this by only using String.format?
For example, I only want the first 6 chars "1234ab" in the result:
int v = 0x1234abcd;
String s = String.format("%06x", v) // gives me 1234abcd
String s = String.format("%06.6x", v) // gives me IllegalformatPrecesionException
The Java Formatter doc said the precision could be used to limit the overall output width, but only to certain data types.
Any ideas? Thanks.
Depending how may hex digits you want to truncate...
You can divide by powers of 16
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
// This will truncate the 2 right most hex digits
String hexV = Integer.toHexString(v / (int)Math.pow(16, 2));
System.out.println(hexV);
}
Results:
1234ab
Even if you mess up and divide by a power of 16 that exceeds the length of your hex string, the result will just be zero.
Then there's the substring() approach
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
String hexV = Integer.toHexString(v);
// This will truncate the the 2 most right hex digits
// provided the length is greater than 2
System.out.println(hexV.length() > 2 ? hexV.substring(0, hexV.length() - 2) : hexV);
}
Since you wanted to do this with just the Formatter.
Here's my result.
1234ab
1234abcd
And here's the code.
public class Tester {
public static void main(String[] args) {
int v = 0x1234abcd;
String s = String.format("%6.6s", String.format("%x", v));
System.out.println(s);
s = String.format("%10.10s", String.format("%x", v));
System.out.println(s);
}
}
I convert the hex number to a String, then truncate or left pad the String with the second Formatter.

java.lang.NumberFormatException: Converting string to ASCII

I am trying to convert my string to ASCII value through my hash function, which looks like this:
public long hash(String word){
StringBuilder sb = new StringBuilder();
String ascString = null;
long asciiInt;
for(int i=0;i<word.length();i++){
sb.append((int)word.charAt(i));
}
ascString = sb.toString();
asciiInt = Long.parseLong(ascString);
return asciiInt;
}
and later on, I will call it in my insert() method to perform quadratic hashing using a hashTable, and the insert method looks like this:
public void insert(Word word){
int start = (int)(hash(word.text)%tableSize);
int key = start;
int attempt=0;
while(hashTable[key]!=null){
attempt++;
key=(start+(int)Math.pow(attempt,2))%tableSize;
}
hashTable[key]=word;
}
However, it throws the java.lang.NumberFormatException if the string I am trying to convert has more than 6 characters. Can anyone help me fix it or a better ways of coming up with the key value for my hash table?
Thanks!
The value you're attempting to gain (base 10 long) can't be achieved from your string because you've the wrong base. Say the string is "DEADBEEF". Because all digits of DEADBEEF are base 16, you can specify the radix as 16 and use
Long.parseLong(DEADBEEF, 16);
The non-radix method assumes that the string contains a base-10 long when really the number is much longer (DEADBEEF is 3735928559 in base 10). Check your string maybe?

Integer.decode(String s)

class Test{
public static void main(String Args[]){
Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}
This doesn't work with the prefix 0 for binary and for octal with the prefix 0.
What is the correct way to do it?
Looking at the documentation for Integer.decode, I see no indication that binary should work. Octal should work though, with a prefix of just 0:
System.out.println(Integer.decode("010")); // Prints 8
You could handle a binary indicator of "0b" like this:
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
Complete sample code showing binary, octal, decimal and hex representations of 15:
public class Test {
public static void main(String[] args) throws Exception {
String[] strings = { "0b1111", "017", "15", "0xf" };
for (String string : strings) {
System.out.println(decode(string)); // 15 every time
}
}
private static int decode(String text) {
return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
}
}
Integer.decode cannot parse binary, see API. But octal work fine, example:
int i = Integer.decode("011");
As of Java 7, you can use binary literals directly in your code. However, note that these are of type byte, short, int or long (and not String).
int x = 0b111;

Categories