Hello,
A new problem today encrypting some information from mBus protocol. I need to convert Hexadecimal (hex) string to an array of bytes. Here is the solution:
Option 1:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
byte[] byteArray = hexStringToByteArray("FF");
String again = byteArrayToHexString(byteArray);
System.out.println(again );
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static String byteArrayToHexString(byte[] b) {
int len = b.length;
String data = new String();
for (int i = 0; i < len; i++){
data += Integer.toHexString((b[i] >>> 4) & 0xf);
data += Integer.toHexString(b[i] & 0xf);
}
return data;
}
Option 2:
/**
* Generates a hexadecimal string from an array of bytes.
* For example, if the array contains {0x01, 0x02, 0x3E},
* the resulting string will be "01023E".
*
* @param bytes A Byte array
* @return A String representation
*/
public static String toHexString( byte[] bytes )
{
StringBuffer sb = new StringBuffer( bytes.length*2 );
for( int i = 0; i < bytes.length; i++ )
{
sb.append( toHex(bytes[i] >> 4) );
sb.append( toHex(bytes[i]) );
}
return sb.toString();
}
private static char toHex(int nibble)
{
final char[] hexDigit =
{
'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'
};
return hexDigit[nibble & 0xF];
}
}
Option 3:
import javax.xml.bind.DatatypeConverter;
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
Hope help!!
No comments:
Post a Comment