views:

234

answers:

5

Hello,

I am tring to convert a set of strings to a byte[] array. At first, I do something like this to convert a byte array to a string:

public String convertByte(byte[] msg) {
    String str = "";        
    for(int i = 0; i < msg.length; i++) {
        str += (msg[i] + " * ");
    }       
    return str;
}

When I try to convert back to the byte[] array, I don't get the same values as the ones when converted to a String. I originally had something gave me incorrect values.

I am currently trying something along the lines of:

public static byte[] convertStr(String ln)
{
    System.out.println(ln);

    String[] st = ln.split(" * ");
    byte[] byteArray = new byte[23];
    for(int i = 0; i < st.length; i++)
    {
        byteArray[i] = st[i].get byte value or something;
    }

    return byteArray;
}

If I try to use the getbytes() method from the String api, It returns a byte array rather than a byte and this is my problem.

Any help would be much appreciated.

A: 

I don't understand why you are trying to get those bytes by characters. getBytes() and its variants will give you a byte[] array for whole string at once. However, if you want to see how characters are encoded, your approach my be good, but you have to keep in mind, that one character could be encoded in e.g. one to four bytes in some encodings, thus you need a byte array for every character.

Gabriel Ščerbák
+1  A: 
Andreas_D
He wants to convert a set of Strings into a byte array, not a single String.
Fortega
No, this will not work since he's using his own function to convert the byte array to a string, e.g. {0, 1, 2, 3} -> "0 * 1 * 2 * 3 * "
jarnbjo
Stupid me, yes you're right - correct answer for a totally different problem ;) thx for the hint.
Andreas_D
A: 

If you are certain the String will be small enough to fit in one byte, you could do

st[i].getBytes()[0];

however, in most of the cases, your String will probably be bigger, so in these cases it is not possible...

Fortega
+1  A: 

Using Byte.parseByte may help making your second snippet work.

But, unless you have some specific reason to use that kind of representation, I'd encode strings to byte arrays using the Java methods mentioned in other answers.

public static byte[] convertStr(String ln)
{
    System.out.println(ln);

    String[] st = ln.split(" * ");
    byte[] byteArray = new byte[23];
    for(int i = 0; i < st.length; i++)
    {
        byteArray[i] = Byte.parseByte(st[i]);
    }

    return byteArray;
}
abahgat
A: 

If you are sure that the string contains 1 byte, you can do:

byteArray[i] = st[i].getbytes()[0];
rsp