IAmGroot
IAmGroot

Reputation: 13855

Parse String respresentation of byte array in JavaME

I sending a byte array over a REST service. It is being received as String. Here is an extract of it. with start and end tags.

[0,0,0,0,32,122,26,65,0,0,0,0,96,123,26,65,0,0,0,0,192,123,20,65,0,0,0,0,0,125,20,65,71,73,70,56,57,97,244,1,244,1,247,0,0,51,85,51,51,85,102,51,85,153,51,85,204,51,85,255,51,128,0,51,128,51,51,128,102,51,128,153,51,128,204,51,128,255,51,170,0,51,170,51,51,170,102,51,170,153,51,170,204,51,170,255,51,213,0,51,213,51,51,213,102,51,213,153,51,213,204,51,213,255,51,255,0,51,255,51,51,255,102,51,255,153,51,255,204,51]

Now before anyone suggests sending it as a base64 encoded String, that would require Blackberry to actually have a working Base64 decoder. But alas, it fails for files over 64k and Ive tried alsorts.

Anyway this is what ive tried:

        str = str.replace('[', ' ');
        str = str.replace(']', ' ');
        String[] tokens = split(str,",");
        byte[] decoded = new byte[tokens.length];
        for(int i = 0; i < tokens.length; i++)
        {           
            decoded[i] = (byte)Integer.parseInt(tokens[i]);             
        }

But it fails. Where split is like the JAVA implementation found here.

Logically it should work? but its not. This is for JavaME / Blackberry. No Java Answers please (unless they work on javaME).

Upvotes: 1

Views: 329

Answers (3)

user784540
user784540

Reputation:

I recommend to use Base64 encoded string to send byte array.

There's a post with link to Base64 library for J2ME.

This way allows you convert byte array to a string and later you can convert this string to byte array.

Upvotes: 1

esej
esej

Reputation: 3059

Two problems one minor and one that is a pain. Minor:whitespaces (as mentioned by Nikita) Major:casting to bytes ... since java only has unsigned byte, 128 and higher will become negative numbers when casting from int to byte.

    str = str.replace('[',' ');
    str = str.replace(']', ' ');
    String[] tokens = split(str,",");//String[] tokens = str.split(",");
    byte[] decoded = new byte[tokens.length];
    for (int i = 0; i < tokens.length; i++) {
        decoded[i] = (byte) (Integer.parseInt(tokens[i].trim()) & 0xFF);
    }
    for(byte b:decoded) {
        int tmp = ((int)b) & 0xff;
        System.out.print("byte:"+tmp);
    }

(btw:implementing base64 encoder/decoder isn't especially hard - might be "overkill" for your project though)

Upvotes: 2

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

Replace brackets with empty strings, not with spaces:

str = str.replace('[', '');
str = str.replace(']', '');

In your case you have following array:

[" 0", "0", "0", ..., "204", "51 "]

First element " 0" cannot be parsed to Integer.

Upvotes: 1

Related Questions