Bartos
Bartos

Reputation: 1037

JAVA , String to byte array byte size

I've got problem with converting byte array to string and back :) I get byte array from api which is 10 bytes long. When I convert it to String i"m getting String with 20 chars for example "12345678901234567890" so it looks like there are 2 chars on one byte. However when I try to send it back with simply getText() from editText :

String namespace = mNamespaceTv.getText().toString();

byte array created from that string is 20 bytes long, so one char to one byte. I need to send it back again as 10 byte array. Why it happened and how can I solve this ?

Upvotes: 2

Views: 2021

Answers (2)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

It is not really clear what you are asking, but consider that the size of the byte array generated from a String depends from the Charset used.

For example:

"ABC".getBytes("UTF-16")   --> array of size 8
"ABC".getBytes("UTF-8")    --> array of size 3
"ABC".getBytes("US-ASCII") --> array of size 3

Upvotes: 2

Aimee Borda
Aimee Borda

Reputation: 842

If it is a byte[] use new String(mNamespaceTv.getText()) rather than toString()

Upvotes: 0

Related Questions