I'm really stuck. I have two strings (of .length() == 2 each) that
represent a hex value. So "01" represents hex 1 decimal 1 and "23"
represents hex 23 or decimal 35.
I need to convert these to a byte array of hex values. In other words,
I need to convert, say String[]{"01,"23"} to byte[]{0x01,0x23}.
How do i get there from here? Thanks, Rvince
Each char contains two bytes. You can extract them from a char with
ordinary mask/shift operators. From there you can extract the low and
high nibble of each byte. Lookup the corresponding char to display
that nibble in an array. Repeat for each char in the String.
To understand the tools see
http://mindprod.com/jgloss/masking.html
http://mindprod.com/jgloss/shift.html
See
http://mindprod.com/jgloss/hex.html for the source code.
/**
* convert a String to a hex representation of the String,
* with 4 hex chars per char of the original String, broken into byte
groups.
* e.g. "1abc \uabcd" gives "0031_0061_0062_0063_0020_abcd"
* @param s String to convert to hex equivalent
* @return hex represenation of string, 4 hex digit chars per char.
*/
public static String displayHexString ( String s )
{
StringBuilder sb = new StringBuilder( s.length() * 5 - 1 );
for ( int i=0; i<s.length(); i++ )
{
char c = s.charAt(i);
if ( i != 0 )
{
sb.append( '_' );
}
// encode 16 bits as four nibbles
sb.append( hexChar [ c >>> 12 & 0xf ] );
sb.append( hexChar [ c >>> 8 & 0xf ] );
sb.append( hexChar [ c >>> 4 & 0xf ] );
sb.append( hexChar [ c & 0xf ] );
}
return sb.toString();
}
/**
* table to convert a nibble to a hex char.
*/
static final char[] hexChar = {
'0' , '1' , '2' , '3' ,
'4' , '5' , '6' , '7' ,
'8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f'};