0

in my program I receive a bytearray. The first part is actually a string and the second a picture converted into a byte array.
Like this:

<STX>1<US>length of picture<ETX> here are the bytes...  

At the moment I have this to split the part before and after the ETX

string incomingMessage = incomingBytes.toString();

String messagePart = incomingMessage.substring(0, firstETX);
String dataPart = incomingMessage.substring(firstETX, incomingMessage.length());

Afterwards I use

dataPart.getBytes();

To convert it back into a byte array.

But I think converting the bytes containing the image causes some problems, because my program won't convert the bytes to an image.

So how do I get the bytes after the ETX without converting it to a string? Or how do I keep the original bytes so I can use them?

Thx

Robby Smet
  • 4,649
  • 8
  • 61
  • 104
  • so the byte array you get contains actually some ASCII characters at the start and the raw image bytes after that? Or do you receive a string with base64 formatted bytes? – Renard Aug 14 '12 at 14:24
  • Yes, the byte array contains some ASCII characters. Everything after ETX are the bytes of my picture that I need. – Robby Smet Aug 14 '12 at 14:26

2 Answers2

1

You need to find the postion of <ETX> inside your byte array. You can then use that as an offset for BitmapFactory.decodeByteArray

I wasn't able to test this code but you should get the idea.

  final byte[] etxBytes = {'<','E','T','X','>'};
    int i =0 ;
    boolean found = false;
    for (i = 0; !found && (i < (incomingBytes.length-etxBytes.length)); i++){
        found = true;
        for (int j=i; (j-i) < etxBytes.length && found; j++){
            if (etxBytes[j-i]!=incomingBytes[j]){
                found = false;
                break;
            }
        }
    }
    if (found){
        int offset = i + etxBytes.length;
        Bitmap image = BitmapFactory.decodeByteArray(incomingBytes, offset, incomingBytes.length-offset);
    }
Renard
  • 6,909
  • 2
  • 27
  • 23
0

Encode the bytes to a string using base 64 encoding as per this answer and then decode them back to the image.

Community
  • 1
  • 1
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148