int hex=Integer.parseInt(str.trim(),16);
String binary=Integer.toBinaryString(hex);
i have a array of hexadecimal numbers as strings and i want to convert those numbers to binary string, above is the code i used and in there, i get a error as shown below
Exception in thread "main" java.lang.NumberFormatException: For input string: "e24dd004"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at sew1.javascript.main(javascript.java:20)
Maximum Integer in Java is 0x7fffffff, because it is signed.
Use
Long.parseLong(str.trim(),16);
or
BigInteger(str.trim(),16);
instead.
The problem is that e24dd004 is larger than int can handle in Java. If you use long, it will be fine:
String str = "e24dd004";
long hex = Long.parseLong(str.trim(),16);
String binary=Long.toBinaryString(hex);
System.out.println(binary);
That will be valid for hex up to 7fffffffffffffff.
An alternative, however, would be to do a direct conversion of each hex digit to 4 binary digits, without ever converting to a numeric value. One simple way of doing that would be to have a Map<Character, String> where each string is 4 digits. That will potentially leave you with leading 0s of course.
Use BigInteger as below:
BigInteger bigInteger = new BigInteger("e24dd004", 16);
String binary = bigInteger.toString(2);
Or using Long.toBinaryString() as below:
long longs = Long.parseLong("e24dd004",16);
String binary = Long.toBinaryString(longs);
Since java-8, you can treat integers as unsigned, so you could do:
String str = "e24dd004";
int i = Integer.parseUnsignedInt(str, 16);
String binary = Integer.toBinaryString(i); //11100010010011011101000000000100
String backToHex = Integer.toUnsignedString(i, 16); //e24dd004
You would be able to handle values that are not larger than 2^32-1 (instead of 2^31-1 if you use signed values).
If you can't use it, you'll have to parse it as a long like other answers showed.
Related
I know that I can add left zeros to String but what about Long?
I need to put left zeros until the Long size is 10 digits. For example, if it's 8 digits (12345678), it should add 2 left zeros (0012345678)
I want to add this in the getValue() method.
public Long getValue() {
// Should always be 10 digits, If it's 8, add zeros
return value;
}
I'm using spring. This issue is that the database that cuts the left zeros. Maybe is there a annotation to avoid extra code?
This is not possible. A Long does not contain data about the String representation of its value. In fact, the Long is actually stored in binary, not decimal, and the long object is unaware of this.
If you want to convert it to a String with leading zeroes, String.format("%017d" , number); will pad it to make sure it has 10 digits.
In java, a long (wrapped in a Long) will always be stored on 8 bytes,
There is no way to "add" extra zeros as they're already existing.
Either your database must change its type to String and add padding zeros when you store your Long object either change your inner code to String and add padding zeros when you pull the data from your Long in db.
You cannot because a long does not have a leading zero.
A string of characters like 0012345678 is not an integer, 12345678 is.
but there are two way in java to add leading zeroes
WAY 1: format() method
int number = 9;
String str = String.format("%04d", 9); // 0009
System.out.printf("original number %d, numeric string with padding : %s", 9, str);
WAY 2 : DecimalFormat
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // 0009
String a = df.format(99); // 0099
String b = df.format(999); // 0999
but in both case you get string instead of Long
for more reading
Try this one,
int number = 12345678;
String str = String.format("%10d", number);
System.out.println("original number %d, numeric string with padding : %s", number, str);
I have seen several questions on the topic mentioned in the subject (e.g this one), but it seems to me that none of them provided this example. I'm using Java7 and I want to convert a String representing an hexadecimal or a decimal into an Integer or Long value (depends on what it represents) and I do the following:
public Number getIntegerOrLong(String num) {
try {
return Integer.decode(num);
} catch (NumberFormatException nf1) {
final long decodedLong = Long.decode(num);
if ((int) decodedLong == decodedLong) {//used in Java8 java.util.Math.toIntExact()
return (int) decodedLong;
}
return decodedLong;
}
}
When I use a String representing a decimal number everything is ok, the problem are arising with negative hexadecimals
Now, If I do:
String hex = "0x"+Integer.toHexString(Integer.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Integer):
fails, because it returns a Long. Same for other negative integer values.
Moreover, when I use Long.MIN_VALUE like in the following:
String hex = "0x"+Integer.toHexString(Long.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Long):
fails, because of NumberFormatException with message:
java.lang.NumberFormatException: For input string: "8000000000000000"
I also tried with other random Long values (so within the Long.MIN_VALUE and Long.MAX_VALUE, and it fails as well when I have negative numbers. E.g.
the String with the hexadecimal 0xc0f1a47ba0c04d89 for the Long number -4,543,669,698,155,229,815 returns:
java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
How can I fix the script to obtain the desired behavior?
Long.decode and Integer.decode do not accept complemented values such as returned by Integer.toHexString : the sign should be represented as a leading - as described by the DecodableString grammars found in the javadoc.
The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Long.parseLong method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign
If you can change the format of your input String, then produce it with Integer.toString(value, 16) rather than Integer.toHexString(value).
If you can switch to Java 8, use parseUnsignedInt/Long.
I have a String encoded in this kind of format:
223175087923687075112234402528973166755
The decoded string looks like:
a7e5f55e1dbb48b799268e1a6d8618a3
I need to convert from Decimal to Hexadecimal, but the input number is much bigger than the int or long types can handle, so how can I convert this?
You can use BigInteger :
BigInteger big = new BigInteger("223175087923687075112234402528973166755");
System.out.println(big.toString(16));
Output :
a7e5f55e1dbb48b799268e1a6d8618a3
I want to convert a Hex String to decimal, but I got an error in the following code:
String hexValue = "23e90b831b74";
int i = Integer.parseInt(hexValue, 16);
The error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "23e90b831b74"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
23e90b831b74 is too large to fit in an int.
You can easily see that by counting the digits. Each two digits in a hex number requires a single byte, so 12 digits require 6 bytes, while an int only has 4 bytes.
Use Long.parseLong.
String hexValue = "23e90b831b74";
long l = Long.parseLong(hexValue, 16);
I have the following code
temp = "0x00"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));
Why do I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "0x00"
Since the string contains 0x, use Integer.decode(String nm):
String binAddr = Integer.toBinaryString(Integer.decode(temp));
Because the leading 0x is not part of a valid base-16 number -- it's just a convention to indicate to a reader that a number is in hex.
Get rid of the '0x': from the javadocs:
The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.
BigInteger.toString(radix) will solve this issue
Refer method description
Hope it helps.
The 0x is for integer literals, eg:
int num = 0xCAFEBABE;
but is not a parseable format. Try this:
temp = "ABFAB"; // without the "0x"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));