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

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

Related

Long to hex String number of characters

Hi i am trying to build a random 16 characters hex, to do so i tried a Long.toHexString(new Random().nextLong() my assumption is that it will always return a 16 chars string, Am i right ? (Once it returned 15 chars)
Take a look at the javadocs for toHexString(long i) (emphasis mine).
public static String toHexString(long i)
Returns a string
representation of the long argument as an unsigned integer in base 16.
The unsigned long value is the argument plus 264 if the argument is
negative; otherwise, it is equal to the argument. This value is
converted to a string of ASCII digits in hexadecimal (base 16) with no
extra leading 0s. If the unsigned magnitude is zero, it is represented
by a single zero character '0' ('\u0030'); otherwise, the first
character of the representation of the unsigned magnitude will not be
the zero character.
As it turns out, it will not always be 16 characters long. However you can pad with zeros if you want like so:
import java.util.Random;
class Main {
public static void main(String[] args) {
String hex16Chars = String.format("%016X", new Random().nextLong());
System.out.println(hex16Chars + ", len: " + hex16Chars.length());
}
}
You will see the length is always 16 as expected.
And it also turns out peeking at the docs actually helps! :)
Referring to Javadoc of the method in question should be your first port of call:
This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s
So no, it won't always be 16 chars.
However, you can print a 16-char uppercased hex string, with leading zeros, using:
String.format("%016X", longValue)

How do I parse a hex-int from a string to an Integer?

I have no problem in writing this: (it also doesn't give any errors)
int hex = 0xFFFFFFFF;
The integer has to have an alpha value also!
But when I try to do this:
Integer hex = Integer.parseInt("0xFFFFFFFF");
// Or I try this:
Integer hex = Integer.parseInt("FFFFFFFF");
I get a java.lang.NumberFormatException: For input string: "0xFFFFFFFF" thrown!
Why is this not working?
I'm guessing that there is some other way to parse hex integers that I am just not realizing, and I really need to be able to parse hex from string for a program I am making.
There is actually a separate function where you can define the radix:
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)
Integer.parseInt(x) simply calls Integer.parseInt(x, 10), so you have to specify a radix 10 number.
In order to parse a hex string, you would simply have to use the following (note that the 0x prefix is not allowed):
Integer.parseInt("FFFFFFF", 16);

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

String binary to Hex 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

Is J2ME's Integer.parseInt() broken?

While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt()
We have several constant values defined as hex values, for example:
CHARACTER_RED = 0xFFAAA005;
During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following:
// Response contains the value "ffAAA005" for "characterId"
string hexValue = response.get("characterId");
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
Then I ran some tests and tried this:
string hexValue = Integer.toHexString(0xFFAAA005);
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
This is the exception from the actual code:
java.lang.NumberFormatException: ffaaa005
at java.lang.Integer.parseInt(Integer.java:462)
at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109)
This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?).
Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation.
In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided?
EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The String you are parsing is too large to fit in an int. In Java, an int is a signed, 32-bit data type. Your string requires at least 36 bits.
Your (positive) value is still too large to fit in a signed 32-bit int.
Do realize that your input (4289372165) overflows the maximum size of an int (2147483647)?
Try parsing the value as a long and trim the leading "0x" off the string before you parse it:
public class Program {
public static void main(String[] args) {
String input = "0xFFFAAA005";
long value = Long.parseLong(input.substring(2), 16);
System.out.print(value);
}
}
I'm not a java dev, but I'd guess parseInt only works with integers. 0xFFFAAA005 has 9 hex digits, so it's a long, not an int. My guess is it's complaining because you asked it to parse a number that's bigger than it's result data type.
Your number seems to be too large to fit in an int, try using Long.parseLong() instead.
Also, the string doesn't seem to get parsed if you have 0x in your string, so try to cut that off.

Categories