Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

conversion hex-string to byte array

807603Sep 2 2005 — edited Feb 22 2008
Hi,

i've found a nice function which converts my byte array to a hex string.
   static char[] hexChar = {
	        '0' , '1' , '2' , '3' ,
	        '4' , '5' , '6' , '7' ,
	        '8' , '9' , 'A' , 'B' ,
	        'C' , 'D' , 'E' , 'F' 
   };

	public static String toHexString ( byte[] b ) {
	    StringBuffer sb = new StringBuffer( b.length * 2 );
	    for ( int i=0; i<b.length; i++ ) {
	        // look up high nibble char
	        sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] ); // fill left with zero bits

	        // look up low nibble char
	        sb.append( hexChar [b[i] & 0x0f] );
	    }
	    return sb.toString();
   }
It's working fine, but i need the conversion in the other direction. It should be very easy, but i didn't get it.
I first tried to use simply
 byte[] bArray = hexStr.getBytes();
but it seems to be something different.

But why is it different?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 21 2008
Added on Sep 2 2005
9 comments
2,063 views