mik3y / usb-serial-for-android

Android USB host serial driver library for CDC, FTDI, Arduino and other devices.
MIT License
4.82k stars 1.58k forks source link

Sending data as Hex format #482

Closed sureshram25 closed 1 year ago

sureshram25 commented 1 year ago

Thanks for the providing the such wonderful library. I am using your library for the serial port communication is working fine. am communicating the microcontroller to send and receive date using the library. Here am sending the data in the form of byte array and receiving the data in the form of the byte array as your library instruct.

Question is, I need to write the data in hex format. Is it possible to write(send) the data in hex format.

sureshram25 commented 1 year ago

Now am able to sent the data in the hexadecimal format. using the below methods Activity class: StringBuilder sb = new StringBuilder(); HexDump.toHexString1(sb, HexDump.fromHexString(str)); msg = sb.toString(); data = HexDump.fromHexString(msg); usbSerialPort.write(data,WRITE_WAIT_MILLIS);

public static void toHexString1(StringBuilder sb, final byte[] buf) { toHexString2(sb, buf, 0, buf.length); }

public static byte[] fromHexString(final CharSequence s) {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    byte b = 0;
    int nibble = 0;
    for(int pos = 0; pos<s.length(); pos++) {
        if(nibble==2) {
            buf.write(b);
            nibble = 0;
            b = 0;
        }
        int c = s.charAt(pos);
        if(c>='0' && c<='9') { nibble++; b *= 16; b += c-'0';    }
        if(c>='A' && c<='F') { nibble++; b *= 16; b += c-'A'+10; }
        if(c>='a' && c<='f') { nibble++; b *= 16; b += c-'a'+10; }
    }
    if(nibble>0)
        buf.write(b);
    return buf.toByteArray();
}