0

Code for the same:

public byte[] stringToBytesUTFCustom(String str) {
    char[] buffer1 = str.toCharArray();
    byte[] b = new byte[buffer1.length << 1];
    for(int i = 0; i < buffer1.length; i++) {
        int bpos = i << 1;
        b[bpos] = (byte) ((buffer1[i]&0xFF00)>>8);
        b[bpos + 1] = (byte) (buffer1[i]&0x00FF);
    }
    return b;
}
public String bytesToStringUTFCustom(byte[] bytes) {
    char[] buffer = new char[bytes.length >> 1];
    for(int i = 0; i < buffer.length; i++) {
        int bpos = i << 1;
        char c = (char)(((bytes[bpos]&0x00FF)<<8) + (bytes[bpos+1]&0x00FF));
        buffer[i] = c;
    }
    String txt = String.valueOf(buffer);
    //return new String(buffer);
    return txt;
}

First, I implement a SMS encryption app (Client to Client) and then want to encode cipher(format "Byte[]") to string, Base64 it's work but can't send because more than 160 character. I'm want to convert byte array to string ,when use function above it's work for same function, but when I use bytesToStringUTFCustom and then send this text(SMS) can't work. Receiver cannot read a text to decode from.

Cipher is a result of bytesToStringUTFCustom function, so anyone can help me? Thanks.

1 Answer 1

3

Did you know these:

You can use Charset.forName(String) to get the Charset.

Charset UTF8 = Charset.forName("UTF-8");
byte[] bytes = str.getBytes(UTF8);
String reverted = new String(bytes, UTF8);
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Why roll your own?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.