The following piece of code I wrote converts a string to a byte. It works but it looks awful. Can this be done in an easier way?
byte stringToByte(String s){ // Converts a string containing a byte on format ["0","255"] // to Java byte format [-128,127]. byte b = 0; if(Integer.parseInt(s) > 255 | | Integer.parseInt(s) < 0){<br /> System.out.println("Byte format expected. " +<br /> Integer.parseInt(s) + " is out of range.");<br /> }<br /> else<br /> {<br /> int n = Integer.parseInt(s);<br /> if( n > Byte.MAX_VALUE) n = n - 256; Integer N = new Integer(0); s = String.valueOf(n); N = Integer.valueOf(s); b = N.byteValue(); } return b; };
I didn't read your code, but are you looking for String.getBytes()?
Mikael Jonasson
Ranch Hand
Joined: May 16, 2001
Posts: 158
posted
0
Try s.charAt(0). /Mike
Daniel Ringstrom
Greenhorn
Joined: Dec 03, 2001
Posts: 3
posted
0
No that doesn't work. For example for the string "67" the method String.getBytes() returns 54 55 (ascii). What I want to do is to return 67 as a byte. The string "67" -> 67, "255" -> -1, "128" -> -128, "127" -> 127 ...
karl koch
Ranch Hand
Joined: May 25, 2001
Posts: 388
posted
0
hi, is this doing the trick for you ?
karl
Daniel Ringstrom
Greenhorn
Joined: Dec 03, 2001
Posts: 3
posted
0
Thank you Karl. That was exactly what I was looking for. /Daniel
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
posted
0
Why use Integer.parseInt(), risking overflow, when there's Byte.parseByte() ready-made, with error handling built in?
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
Byte.parseByte() will throw a NumberFormatException for Daniel's example of "128". But this opens a larger can of worms - what is the desired input range of the function? If 128 should be converted to -128, then a simple solution is <pre> byte stringToByte(String s){ return (byte) Integer.parseInt(s); } </pre> The question is, if a number is outside the range of a byte, do you want to throw an error, or quietly convert if anyway? Karl's solution assumes 0 < x < 255 is the intended input range, which is a reasonable possibility. (What about the endpoints though?) Lots of possible ways to do this - it all depends on what you really need this function to do. [This message has been edited by Jim Yingst (edited December 03, 2001).]
"I'm not back." - Bill Harding, Twister
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.