-1

I wrote a code to send and receive packet using UDP protocol. When I received int, and I'm sure it's a number, I can't convert it from byte[] - which is the type of received packet - to an int. I tried to convert it from byte[] to String, and from String to int, but the same problem, I got the exception "NumberFormatException". My code to convert is:

  String newtext = new String (receivePacket.getData());
  System.out.println("I receive "+ newtext );
  int location = Integer.parseInt(newtext);

The output shown in console is a number, but the code can't see as a number. Any suggestion to solve it.

user207421
  • 305,947
  • 44
  • 307
  • 483
asma
  • 113
  • 3
  • 11

2 Answers2

0

the code can't see a number

This is completely meaningless as a problem description; however the problem is here:

String newtext = new String (receivePacket.getData());

This should be:

String newtext = new String (receivePacket.getData(),receivePacket.getOffset(),receivePacket.getLength());

However your description is so vague that it's possible you're receiving the int in binary, in which case you need the following instead:

int location = new DataInputStream((receivePacket.getData(),receivePacket.getOffset(),receivePacket.getLength()).readInt();

or possibly readShort().

user207421
  • 305,947
  • 44
  • 307
  • 483
  • thank you for your reply and sorry for the vague in the explanation. Your suggestion doesn't solve my problem, but I think I know more about my problem, which is the when I use the different ways of converting, the whole `Byte[1024]` is converted, not just the `int`, which is the beginning of the array. – asma Mar 27 '18 at 13:16
-1

The problem is solved using to steps: 1. The input int is converted to Byte[4] before sending the packet using this post Convert integer into byte array (Java)

  1. Convert it back from Byte[4] to int using this post http://www.java2s.com/Code/Android/Date-Type/Convertabytearrayinteger4bytestoitsintvalue.htm

Thank you for who tried to help me, hope this help who face the same problem.

asma
  • 113
  • 3
  • 11
  • @EJP, the problem described correctly and the code I was posted is part of the problem. – asma Mar 29 '18 at 10:11