0

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.

1
  • Wouldn't it be easier to reverse bytes? Or even to iterate bytes in the opposite direction? Commented Apr 6, 2012 at 14:47

3 Answers 3

4

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

sb.insert(0, text);

instead of this:

sb.append(text);
Sign up to request clarification or add additional context in comments.

Comments

0

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();

}

1 Comment

oooh!! didnt think of that....gosh i should have^^ thanks anyway, works fine!!! (thanks everybody by the way!!)
0

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

You can read more here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.