String binary to Hex Java - java

i have code that looks like this
public static void main(String[] args) {
String string= "11011100010000010001000000000000";
String string1= "00000000010000110000100000101100";
System.out.println(Integer.toHexString(Integer.parseInt(string1,2)));
System.out.println(Integer.toHexString(Integer.parseInt(string,2)));
}
the first string convert just fine but the second one has an error of java.lang.NumberFormatException
dont know what the problem is

try this:
Long.toHexString(Long.parseLong(string,2))
(edited from parsLong to parseLong)

For what's worth, you can also use the BigInteger class :
String string = "11011100010000010001000000000000";
String string1 = "00000000010000110000100000101100";
System.out.println(new BigInteger(string1, 2).toString(16));
System.out.println(new BigInteger(string, 2).toString(16));

When the most significant bit of a 32-character binary number is set to 1, the resultant value exceeds the range of positive numbers supported by int, and can no longer be interpreted as a valid integer number. This causes the exception according to the documentation:
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
The value represented by the string is not a value of type int. (emphasis is mine)
In order to enter this negative binary value, use - sign in front of your number, and convert the remaining bits to 2-s complement representation.
If you need numbers that are longer than 32 bits, or if you would like the value to continue being interpreted as a positive number, you would need to switch to the 64-bit integer data type.

You can use Long instead of Integer, (Long.parseLong and Long.toHexString methods).

If you want to parse to integer, the range should be
10000000000000000000000000000000 to 01111111111111111111111111111111

Related

How to convert String (byte array as string) to short

Hello here i want to convert Byte array ie 0x3eb to short so i considered 0x3eb as a string and tried to convert to short but its throwing Numberformat Exception...someone please help me
import java.io.UnsupportedEncodingException;
public class mmmain
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String ss="0x03eb";
Short value = Short.parseShort(ss);
System.out.println("value--->"+value);
}
}
Exception what im getting is
Exception in thread "main" java.lang.NumberFormatException:
For input string: "0x3eb" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:491)
at java.lang.Short.parseShort(Short.java:117)
at java.lang.Short.parseShort(Short.java:143)
at mmmain.main(mmmain.java:14)
even i tried converting 0x3eb to bytes by
byte[] bytes = ss.getBytes();
but i didnt found any implementation for parsing bytes to short.
Thanks in advance
See the doc of parseShort:
Parses the string argument as a signed decimal short. The characters
in the string must all be decimal digits, 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 string to be parsed should only contain decimal characters and sign characters, it can not contains the 0x prefix.
Try:
String ss="3eb";
Short value = Short.parseShort(ss, 16);
Since the string value that you're using is a hexadecimal value, to convert it into short, you need to remove the 0x using a substring and pass the radix as below:
Short.parseShort(yourHexString.substring(2), 16)
Here 16 is the radix. More info in the doc here.
Update
Since the OP asked for some more clarification, adding the below info.
The short datatype can only have values between -32,768 and 32,767. It can't directly hold 0x3eb, but it can hold the equivalent decimal value of it. That's why when you parse it into the short variable and print, it shows 1003, which is the decimal equivalent of 0x3eb.
You have to cut "0x" from the beginning:
short.parseShort(yourHexString.Substring(2), 16)
Follow this document this may help you String to byte array, byte array to String in Java

Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception

I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.
Because:
The int data type is a 32-bit signed two's complement integer. It has
a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
Code Throwing the NumberFormatException:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?
Use BigInteger to avoid numeric limits of primitive int and long:
BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16); // Radix 16 indicates hex
System.out.println(x16);
The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.
Demo.
If your input value can be arbitrarily large, then #dasblinkenlight's answer involving BigInteger is your best bet.
However, if your value is less than 263, then you can just use Long instead of Integer:
String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex); // 2540be3ff
Live demo.
Use Integer.parseUnsignedInt
When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:
int n = Integer.parseUnsignedInt("CAFEBABE", 16);
(I used hexadecimal here, as it is easier to see that above we are just in that range.)
However 9_999_999_999 is above the unsigned int range too.
Try this way:
String largeNumberAsAString = "9999999999";
System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));

Java scanner nextInt(16) does not accept negative hex values

I need to read in a 32-bit number in hex format. When I enter a negative value, I get an input mismatch exception. Everything works as long as the number is positive (00000000 ~ 7FFFFFFF), but anything negative (80000000 ~ FFFFFFFF) fails.
System.out.println("Enter first number in hexadecimal format: ");
Scanner readX = new Scanner(System.in);
int a = readX.nextInt(16);
I have tried various formats (FFFFFFFF, 0xFFFFFFFF, -FFFFFFFF, -7FFFFFFFF, ~FFFFFFFF) with the same results.
Any ideas? I feel like I must be missing something obvious but I'm completely stumped!
It will fail for the same reason 2147483648 (one more than Integer.MAX_VALUE) will fail for Integer.parseInt: The value is too large. It will not interpret ffffffff or 80000000 as a negative number, but as a large positive number. Those numbers are simply too large to be interpreted as an int.
Scanner.nextInt(int radix) matches a regular expression to see if it could be an int, then it passes it to Integer.parseInt for parsing:
If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.
Integer.parseInt will throw a NumberFormatException if it can't be represented as an int:
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
The value represented by the string is not a value of type int.
You must specify the number to be negative. Try -1 or -80000000 or anything in between; they will work.
System.out.println("Enter first number in hexadecimal format: ");
Scanner readX = new Scanner(System.in);
String a = readX.nextLine().trim();
int result = Integer.parseInt(a, 16);
This will be work for youThen you get value as scientific notation if it's not fit to int.

java.lang.NumberFormatException: For input string: "10.0"

This code must validate input data from the findActions() method:
try {
System.out.println(findActions(lookingArea.substring(0, right)));// always printing valid number string
Integer.parseInt(findActions(lookingArea.substring(0, right)));// checking for number format
}
catch(NumberFormatException exc) {
System.out.println(exc);
}
But I always have java.lang.NumberFormatException: For input string: "*number*"
that is so strange, because checking with System.out.println(findActions(lookingArea.substring(0, right)));,
I get *number* like 10.0
Integer.parseInt doesn't expect the . character. If you're sure it can be converted to an int, then do one of the following:
Eliminate the ".0" off the end of the string before parsing it, or
Call Double.parseDouble, and cast the result to int.
Quoting the linked Javadocs above:
The characters in the string must all be decimal digits, 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.
10.0 is not an integer number. Instead, you can use:
int num = (int) Double.parseDouble(...);
One of the reason could be that your string is too long to convert into Integer type, So you can declare it as Long or Double based on the provided input.
Long l = Long.parseLong(str);

NumberFormat Exception to parse String to Byte?

I am trying to parse the following String to Byte.But it gives me NumberFormat Exception.Can some body tell me what is the solution for this?
Byte.parseByte("11111111111111111111111110000001", 2);
Byte.parseByte() handles binary string as sign-magnitude not as a 2's complement, so the longest length you can have for a byte is 7 bits with a sign.
In other words, to represent -127, you should use:
Byte.parseByte("-111111", 2);
The following throws NumberFormatException:
Byte.parseByte("10000000", 2);
However, the binary literal of -127 is:
byte b = (byte) 0b10000000;
The same behavior is applied to the other parseXXX() methods.
Out of range of byte ie -128 to 127. From parseByte(String s,int radix) javadoc:
public static byte parseByte(String s, int radix)throws NumberFormatException
Parses the string argument as a signed byte in the radix specified by
the second argument. 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.
The resulting byte value is returned. An exception of type
NumberFormatException is thrown if any of the following situations
occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix,
except that the first character may be a minus sign '-' ('\u002D')
provided that the string is longer than length 1.
The value represented by the string is not a value of type byte.
Returns: the byte value represented by the string argument in the
specified radix Throws: NumberFormatException - If the string does not
contain a parsable byte.
from javadocs
An exception of type NumberFormatException is thrown if any of the
following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D')
provided that the string is longer than length 1.
The value represented by the string is not a value of type byte.
Your value is the second case that is out of range -128 to 127
Value is too large to be parsed in byte
Try this:
new BigInteger("011111111111111111111111110000001", 2).longValue();

Categories