Re: String to byte[] -- I cant get there from here?
RVince wrote:
When I look for String to unsingned byte, I essentially have two
choices, neither of which work.
Take, for instance:
public static void main(String[] args) {
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim());
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
}
This results in :
java.lang.NumberFormatException: For input string: "0F"
Similartly, if I go with:
try{
String s = "0F";
byte u =(byte)Integer.parseInt(s.trim(),16);
System.out.println(u);
}catch(Exception e){
e.printStackTrace();
}finally{
System.exit(0);
}
It results in printing out 15, which is incorrect, it should print out
0F as the value for the byte.
Given that the value of the byte was 15, you don't have anything to complain
about when the println() outputs the correct value. Bear in mind that 15
(decimal) and 0F (hex) are the exact same numeric value.
If you wish to display that numeric value of 15 (decimal) as a string with
hexadecimal characters, you have to do a conversion from the numeric value to
a hex string value.
Did you read the Javadocs for 'System.out.println(int)'?
Prints an integer. The string produced by String.valueOf(int)
is translated into bytes according to the platform's default
character encoding, and these bytes are written ...
'String.valueOf(int)' does:
The representation is exactly the one returned by the
Integer.toString method of one argument.
and 'Integer.toString(int)'?
The argument is converted to signed decimal representation and
returned as a string, exactly as if the argument and radix 10
were given as arguments to the toString(int, int) method.
So the conversion by 'println()' uses radix 10, exactly as documented.
However, that chain of research did lead to the 'Integer.toString(int, int)'
method. You could display the value in base 16 by calling:
System.out.println( Integer.toString( u, 16 ));
Always read the Javadocs!
--
Lew