Below
snippet converts byte array to hexa string.
private
static final char[] HEXDIGITS = "0123456789ABCDEF".toCharArray();
private
static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length
* 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
//sb.append(' ');
}
return sb.toString();
}
Find the
below working application.
App.java
package com.sample.app; public class App { private static final char[] HEXDIGITS = "0123456789ABCDEF".toCharArray(); private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(HEXDIGITS[b >> 4]); sb.append(HEXDIGITS[b & 15]); // sb.append(' '); } return sb.toString(); } public static void main(String args[]) { String str = "Hello World"; String hexaString = toHexString(str.getBytes()); System.out.println("Hexa string for " + str + " is " + hexaString); } }
Output
Hexa string for Hello World is 48656C6C6F20576F726C64
Hexa string for Hello World is 48656C6C6F20576F726C64
You may like
Previous Next Home
No comments:
Post a Comment