0

I got a stream of byte this stream is a bytearray ( byte[] stream ) now i want parse this byte first to an hex value, e.g. 80 = "0x50" then transform this to an int

But for some values like 0xB8 i got an `java.lang.NumberFormatException: For input string: "0xB8"

How could i manage this exception? Maybe with an other type of parse or different type data?

byte k = stream[i];

        int b = 0;
        try {
            b = Integer.parseInt(String.format("0x%02X",k),16);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
  • Check this https://stackoverflow.com/questions/11377944/parsing-a-hexadecimal-string-to-an-integer-throws-a-numberformatexception – mettleap Nov 15 '18 at 17:31

3 Answers3

3

You must use overloaded parseInt method with radix. For hex value an example:

Integer.parseInt("84B",16);
Tix
  • 610
  • 6
  • 16
  • @GianlucaBenucci Check what it returns String.format("0x%02X",k), it can return a non-hex string. – Tix Nov 16 '18 at 07:58
  • 1
    You'll need to remove the leading `0x` for this to work. `Integer.parseInt("84B",16)` returns 2123, but with `0x84B` you get a `NumberFormatException`. – jsheeran Nov 16 '18 at 08:03
0

Try this:

Integer.parseInt(String.format("0b%02X",k),16);

Binary values are written using "0bxx" syntax

Nick
  • 744
  • 6
  • 11
0

I've resolved my problem with this question

byte k = stream[i];

        int b = 0;
        try {
            String hexStringNumber = String.format("0x%02X",k);
            b = Integer.decode(hexStringNumber);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }