Search code examples
javaarrayscastingshorttypecasting-operator

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


Solution

  • 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.