• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception parsing Bytes  RSS feed

 
Gaelle SMITS
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there !

I get an exception trying to build a byte array from a String.
My code is :



Running this code throws me this exception :
Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"A9" Radix:16
at java.lang.Byte.parseByte(Unknown Source)
at fr.cnp.gcs.socle.technique.test.CleanTestKeys.main(CleanTestKeys.java:31)

I'm affraid I d'ont know how to solve this, I think it's something about signed stuff, but I'm no good for this. :roll:

Can someone help me ?

Thanks !!!
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using StringTokenizer, which is now called legacy code? Use String#split instead.

Yes, it must be to do with going out of range. Try using the Integer parse method and casting the result to a byte.

There is probably a still easier way.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A9 is hexadecimal for 169, and bytes can only have values between -128 and 127 (inclusive).

You'll have to use Integer.parseInt, then cast to byte:

The parseInt will return the integer 169, or in binary
0000 0000 0000 0000 0000 0000 1010 1001

If you cast it to byte, it will discard everything except 1010 1001. That's the binary representation of -87.
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A String character (Unicode) is two bytes long. (a total of 64K different values)
When trying to convert a character to a type byte (which only holds values from -128 to 127) there will be a lot of String characters that are outside the valid range of byte values, hence the Exception
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!