convert from binary to hex in java?

hi i need to convert binary data to hex data to send an mms throw XML file to the operator, it worked with the text and audio but converting the images is not working can any body help me heres my code

public static String toHexEncodedString(byte[] data) {

StringBuffer dataStr = new StringBuffer();

int counter = 0;

for (int i = 0; i < data.length; i++) {

if ((char) data[i] == '|' && counter < 2) {

dataStr.append((char) data[i]);

counter++;

} else {

String s = Integer.toHexString(data[i]).toUpperCase();

if ((data[i] >= 0) && (data[i] <= 0x0F)) {

s = '0' + s;

} else if (data[i] < 0) {

s = Integer.toHexString(data[i] & 0xFF).toUpperCase();

}

dataStr.append(s);

}

Update:

:) i found the answer

public static String toHexString ( byte[] b )

{

StringBuffer sb = new StringBuffer( b.length * 2 );

for ( int i=0; i<b.length; i++ )

{

// look up high nibble char

sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] );

// look up low nibble char

sb.append( hexChar [b[i] & 0x0f] );

}

return sb.toString();

}

// table to convert a nibble to a hex char.

static char[] hexChar = {

'0' , '1' , '2' , '3' ,

'4' , '5' , '6' , '7' ,

'8' , '9' , 'a' , 'b' ,

'c' , 'd' , 'e' , 'f'};

3 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    hi i need to convert binary data to hex data to send an mms throw XML file to the operator, it worked with the text and audio but converting the images is not working can any body help me heres my code

    public static String toHexEncodedString(byte[] data) {

    StringBuffer dataStr = new StringBuffer();

    int counter = 0;

    for (int i = 0; i < data.length; i++) {

    if ((char) data[i] == '|' && counter < 2) {

    dataStr.append((char) data[i]);

    counter++;

    } else {

    String s = Integer.toHexString(data[i]).t...

    if ((data[i] >= 0) && (data[i] <= 0x0F)) {

    s = '0' + s;

    } else if (data[i] < 0) {

    s = Integer.toHexString(data[i] & 0xFF).toUpperCase();

    }

    dataStr.append(s);

    }

  • parke
    Lv 4
    4 years ago

    Java Hex To Binary

  • 4 years ago

    Hex To Binary Java

Still have questions? Get your answers by asking now.