Convert hex to bytes and viceversa   #


import java.util.*; import java.lang.*; import java.io.*; // Number Utils convert hex to bytes and viceversa class NumberUtils { // hex to byte[] public static byte[] hex2Byte(String str) { byte[] bytes = new byte[str.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer .parseInt(str.substring(2 * i, 2 * i + 2), 16); } return bytes; } // bytes to hex public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } if (n < (b.length - 1)) { hs = hs + ""; } } return hs; } public static void main (String[] args) throws java.lang.Exception { // convert to bytes String num ="ff00ff"; byte[] bytes = NumberUtils.hex2Byte(num); System.out.println("Num " + num + " as hex to bytes = " + bytes); // convert back to hex String numBack = NumberUtils.byte2hex(bytes); System.out.println("Bytes " + bytes + " as hex number = " + numBack); if (numBack.equals (num)) { System.out.println("Hex to bytes and back to hex works!"); } } }

Loading Please Wait...