Hex to binary conversion java - java

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));

Related

Why does the java accepts integer with a '+' sign and how to not accept integer input with a '+' sign

Why does the java accepts integer with a '+' sign and how to not accept integer input with a '+' sign. Please help! Thanks in advance
nAmount= scan.nextInt();
String sAmount = Integer.toString(nAmount);
//ON THIS LINE, MY PROG SHOULD NOT ACCEPT INTEGERS WITH "+" SIGN
if (sAmount.contains("+")) {
System.out.println("金額に文字が入力されています。");
} else if (nAmount<=0) {
System.out.println("金額は0円以上で入力してください。");
} else if (nAmount>999999) {
System.out.println("金額は999,999円以下で入力してください。");
} else nAFlag =1;
Sample Output :
Input > 100 (Accepted)
Input > -100 (Not Accepted because of the constrain input is less than 0)
Input > +100 (IT SHOULD NOT BE ACCEPTED BECAUSE IT CONTAINS A SYMBOL)
You are reading an int using Scanner.nextInt(): as described in the documentation, this uses Integer.parseInt to read the number; and that method explicitly states that it accepts a leading + sign:
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
And once you've read that number, there's no way to distinguish the fact that you entered 123 or +123, because there's no difference in the value. So, you've lost the + even before you convert the int to a String.
To capture this, you need to read the String first, and convert that to an int:
String sAmount= scan.next();
nAmount = Integer.parseInt(sAmount);
This preserves the + sign in sAmount, because there is no reason to strip it away. Note that it will fail if sAmount can't actually be parsed as an int.

Converting Hex in Java, wrong value with negative values

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.

Why does Integer.parseInt("\uD835\uDFE8") fail?

I was under the impression that java supports unicode characters. I made this test and sadly found that it fails. The question is why? Is it a bug or somewhere documented?
// MATHEMATICAL SANS-SERIF "𝟨"
String unicodeNum6 = "\uD835\uDFE8";
int codePoint6 = unicodeNum6.codePointAt(0);
int val6 = Character.getNumericValue(codePoint6);
System.out.println("unicodeNum6 = "+ unicodeNum6
+ ", codePoint6 = "+ codePoint6+ ", val6 = "+val6);
int unicodeNum6Int = Integer.parseInt(unicodeNum6);
This fails with a Exception in thread "main" java.lang.NumberFormatException: For input string: "𝟨"
Unexpected I think, since the println works and prints the expected line:
unicodeNum6 = 𝟨, codePoint6 = 120808, val6 = 6
So Java perfectly knows the numerical value of the unicode character but does not use it in parseInt.
Can someone give a good reason why it should fail?
It's not bug, the behaviour is documented. According to the documentation for parseInt(String s, int radix) (emphasis mine)
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
If you try :
int aa = Character.digit('\uD835', 10);
int bb = Character.digit('\uDFE8', 10);
You'll see that both return -1.
Mind you, Integer.parseInt(unicodeNum6); will just call Integer.parseInt(unicodeNum6, 10);

Java - Construct a signed numeric String and convert it to an integer

Can I somehow prepend a minus sign to a numeric String and convert it into an int?
In example:
If I have 2 Strings :
String x="-";
String y="2";
how can i get them converted to an Int which value is -2?
You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.
Therefore this will print -2 the way you want it:
String x = "-";
String y = "2";
int i = Integer.parseInt(x + y);
System.out.println(i);
Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.
Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.
If you're trying to get a character code, use the following:
(int) "-".charAt(0);
charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

ParseInt NumberFormatException on phone number

I'm getting the following error when trying to parse the phone number, "5554567899"
java.lang.NumberFormatException: For input string: "5554567899"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
...
Obviously, the phone number is able to be parsed. I even referenced this question, and the byte code result was
53,53,53,52,53,54,55,56,57,57,
So there's no invisible characters in the string. I'm stumped, can anyone help?
Here's the section of the code that's throwing the error, for reference:
String fullNumber = null;
for(Phone phone : party.getPhones()) {
if(phone != null && !phone.getDialNumber().isEmpty()) {
if(!phone.getAreaCode().isEmpty()) {
fullNumber = phone.getAreaCode();
}
fullNumber += phone.getDialNumber();
if(phone1 == null || phone1.equals(0)) {
LOGGER.debug(displayCharValues(fullNumber));
phone1 = Integer.parseInt(fullNumber);
}
}
phone1 is of Java.lang.Integer type.
The value exceeds the int range. Parse it into a long variable.
Simple test:
int i = 5554567899;
is a compile time error: "The literal 5554567899 of type int is out of range"
Really a phone number shouldn't be treated as a number at all, but as a string or possibly as a datatype that you define yourself, breaking out the country code, area code, exchange, etc.
If you want to validate that it contains only numbers or numbers plus some of the standard phone-number separators, this can be done by regular expressions.
We call it a phone number, and it is a numeric string, but as the usage isn't for numeric computation, you're better off never trying to treat it as a number.
The same goes for "social security numbers".
5554567899 as a number is too big to fit in an int. Try Long.parseLong instead.
5554567899 exceeds Integer.MAX_VALUE (2147483647). Use Long or BigInteger instead:
BigInteger bigNumber = new BigInteger("5554567899");

Categories

Resources