2

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 ?

7
  • 1
    Very unclear what you're actually asking. How can you encode 20 bytes in 10 bytes? (Short of compressing it) Commented Dec 7, 2016 at 11:06
  • See stackoverflow.com/questions/1536054/… Commented Dec 7, 2016 at 11:07
  • @AndyTurner I don't want to encode anything. Just try to understand what happened. Commented Dec 7, 2016 at 11:10
  • 1
    I suspect you represent the byte as Hex, In Hex, one byte will usually be represented by 2 "digits" 0-F for example "8F" => 1 byte = 2 chars ... Each of which will be represented by 1 byte in UTF-8 or ASCII. Commented Dec 7, 2016 at 11:10
  • 1
    "I don't want to encode anything" - I guess you did accidentally. Commented Dec 7, 2016 at 11:15

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.