prasan.sree
prasan.sree

Reputation: 41

want to send hexadecimal string data in java

I have Integer data in char[] array. example: 12, 03, 10. I want to sent the data as hexadecimal format in string.

example : 0C030A

But after converting into hexadecimal, I am getting C3A.
kindly suggest me to get the right data as 0C030A.

I am using the following code

String messageBody = "A3";
SimpleDateFormat sdf = new SimpleDateFormat("MM:dd:yy:HH:mm:ss");
String currentDateandTime = sdf.format(new Date(mLocation.getTime()));
char[] temp;
temp = currentDateandTime.split(delimiter);
for( int i = 0; i < temp.length; i++ )
{
    messageBody += Integer.toHexString (Integer.parseInt( temp[i]));
}

Upvotes: 4

Views: 995

Answers (2)

robert
robert

Reputation: 4867

String.format() can be fairly heavyweight where performance is a concern (lots of orphan objects created and immediately thrown away).

If you want something a little tighter you can do something like this:

final StringBuilder sb = new StringBuilder("0x00000000");
String fmt(int item) {

    int tmp;
    char c;

    for (int i = 9; i >= 2; i--) {

        tmp = (item & 0xF); item >>= 4;
        c = (char) (tmp < 10 ? '0' + tmp : 'A' + tmp - 10);
        sb.setCharAt(i, c);
    }

    return sb.toString();
}

you could optimise this even further (ie use less variables and perform less iterations), but I think this is exhaustive enough for now :) not Thread-safe etc.

Upvotes: 0

kichik
kichik

Reputation: 34744

You can use String.format() with "%02x" for that. 02 means pad with zeros until length of 2. x means hex.

messageBody += String.format("%02x", Integer.parseInt(temp[i]));

Upvotes: 4

Related Questions