Guigui
Guigui

Reputation: 147

reversing a string two char by two char

I'm trying to develop a program that convert 6 bytes into a hexadecimal representation (like 00:65:36:21:A5:BC)

with this method :

public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(18);
        for (byte b : bytes) {
            if (sb.length() > 0)
                sb.append(':');
            sb.append(String.format("%02x", b));
        }

        return sb.toString();

    }

I'm obtaining a good format, but now I have to reverse the digits two by two.

what I obtain 00:65:36:21:A5:BC

what I should get BC:A5:21:36:65:00

Can anybody help me on that final step ?? I'm struggling to take each pair of digits and reverse its position (putting BC at the beginning, but without changing its order (like CB)

Thanks in advance

G.

Upvotes: 0

Views: 234

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76444

Use the insert method of the StringBuilder class instead of the append method, with an offset of 0.

You can read more here.

Upvotes: 0

Guedes
Guedes

Reputation: 189

You can use a reverse regular for instead of a for each

public static String toHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder(18);
    for (int i = bytes.length - 1; i >= 0; i--) {
        if (sb.length() > 0)
            sb.append(':');
        sb.append(String.format("%02x", bytes[i]));
    }

    return sb.toString();

}

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117587

To append at the beginning rather than appending to the last, use this:

sb.insert(0, text);

instead of this:

sb.append(text);

Upvotes: 4

Related Questions