Want to send hex string data to java

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

example: 0C030A

But after converting to hex, I get C3A.
kindly suggest me get the correct data like 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])); } 
+4
source share
2 answers

You can use String.format() with "%02x" for this. 02 means padding with zeros as long as length 2. x does not mean hex.

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

String.format() can be pretty heavyweight when performance is troubling (lots of orphaned objects created and dropped right away).

If you want something a little more stressful, 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 optimize it even further (i.e. use fewer variables and perform fewer iterations), but I think this is exhaustive enough now :) is not thread protected, etc.

0
source

Source: https://habr.com/ru/post/1443707/


All Articles