I need to pass an attachment into an ABAP RFC and need to change the bytes into a hex string. I have a small java routine to do this. However it takes 5 minutes to convert 245kb of data.
This seems very slow. Any guidance on how this conversion can be done quickly as I have to convert up to 5Mb of data.
Create a BigInteger using the byte array
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(16);
if (s.length() % 2 != 0) {
//Pad with 0
s + “0”+s;
}
I now split the byte array up into smaller chunks before converting and this has speeded things up a bit.
I also have the problem that my JPG file is creating a negative BigInteger and this is giving me a “0-” start to my hex string which I don’t quite understand
Not sure if this is what you need, but a book I bought recently had this class as part of a utilities package.
Mark
[highlight=java]
public class Utils
{
private static String digits = “0123456789abcdef”;
/**
* Return length many bytes of the passed in byte array as a hex string.
*
* @param data the bytes to be converted.
* @param length the number of bytes in the data block to be converted.
* @return a hex representation of length bytes of data.
*/
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++)
{
int v = data[i] & 0xff;
buf.append(digits.charAt(v >> 4));
buf.append(digits.charAt(v & 0xf));
}
return buf.toString();
}
/**
* Return the passed in byte array as a hex string.
*
* @param data the bytes to be converted.
* @return a hex representation of data.
*/
public static String toHex(byte[] data)
{
return toHex(data, data.length);
}
Mark beat me to the punch. The utils he posted are the way to go. String operations are notoriously inefficient, since String objects are immutable there’s a lot of time spent allocating objects. Using the “+” operator creates new String objects
Give the code Mark posted a try. You should see some good gains, though probably not 5 minutes worth.