Convert Byte Array to Charsequence in Android

Andro Selva picture Andro Selva · Aug 21, 2012 · Viewed 16.6k times · Source

I have used the below code to convert Charsequence to Byte Array. Then I save the Byte Array as Blob to my Sqlite Database.

For this , I have used the below code,

 public static byte[] toByteArray(CharSequence charSequence) {
        if (charSequence == null) {
          return null;
        }
        byte[] barr = new byte[charSequence.length()];
        for (int i = 0; i < barr.length; i++) {
          barr[i] = (byte) charSequence.charAt(i);
        }

        return barr;
      }

Now I would like to convert my byte array retrieved from sqlite to Charsequence. But I couldn't get any help on it.

How to convert Byte Array to Charsequence?

Any help is much appreciated.

Answer

Stephen Connolly picture Stephen Connolly · Aug 21, 2012

To convert a CharSequence into a byte array

CharSequence seq;
Charset charset;
...
byte[] bytes = seq.toString().getBytes(charset);

To convert back again

CharSequence seq2 = new String(bytes, charset);

Just remember that CharSequence is an interface that is implemented by String, StringBuilder, StringBuffer, etc so all String instances are CharSequence instances but not all CharSequence instances are String but the contract for CharSequence is that its toString() method should return the equivalent String

Internally all strings in Java are represented as Unicode, so as long as the consumer and producer are both Java the safest charset to use is one of UTF-8 or UTF-16 depending on the likely encoding size of your data. Where Latin scripts predominate,

Charset charset = Charset.forName("UTF-8"); 

will 99.9% of the time give the most space efficient encoding, for non-latin character sets (e.g. Chinese) you may find UTF-16 more space efficient depending on the data set you are encoding. You would need to have measurements showing that it is a more space efficient encoding and as UTF-8 is more widely expected I recommend UTF-8 as the default encoding in any case.