Search code examples
androidarduinoserial-portinputstreambytearrayoutputstream

how to convert input stream to byte array to string in android


I'm working on RFID serial port. In this I have a source code in that mentioned like this new SerialPort(new File("/dev/ttyS3"), 19200); its working perfect I am getting an output, but not in good encoding I tried all encodings, but it's not working.

I am getting an output from InputStream:

mInputStream = mSerialPort.getInputStream();

private byte[] reciveBuffer=new byte[128];;
private int size = 0;

size = mInputStream.read(reciveBuffer);
 //i checked all encodings
String message = new String(reciveBuffer,0, size,Charset.forName("iso-8859-1"));
String message2 = new String(reciveBuffer,0, size,Charset.forName("windows-1252"));

assert message2.charAt(1) == '\u00E4';
String message3 = new String(reciveBuffer,0, size,Charset.forName("US-ASCII"));
String encode=((reciveBuffer[0] & 128) == 0) ? "UTF-8" : "windows-1252";
String display = new String(reciveBuffer, 0, size);

But in string I'm getting:

3������`������`��xf���f���

from all encodings.


Solution

  • You can try following function:

    private String Buff2String(byte[] buff) {
        String retVal = "";
    
        for(byte c : buff) {
            int i = c & 0xFF;
            retVal += (char)i;
        }
    
        return retVal;
    }