Jun 02

You can use BigInteger class to convert a byte array into its hex (or binary) representation. However for large byte arrays this method is slow.

For large byte arrays and where performance is important you can use the following utility method to convert each byte to its binary representation.

   public static String toBinaryString(byte n) {
        StringBuilder sb = new StringBuilder("00000000");
        for (int bit = 0; bit < 8; bit++) {
            if (((n >> bit) & 1) > 0) {
                sb.setCharAt(7 - bit, '1');
        return sb.toString();

written by objects \\ tags: , , , ,

May 02

Java Strings are immutable (cannot be changed) so reversing a String requires creating a new String.

A loop can be used to build the reversed string by adding the characters from original string in reverse order, but the StringBuilder class provides a reverse() method to do it for us.

The following example shows its usage.

String s = "The string to be reversed";
StringBuilder sb = new StringBuilder(s);
String reversed = sb.toString();

written by objects \\ tags: , ,