Monday, October 12, 2015

java - How to convert a string to a byte array

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set background color for action bar
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initialize a new string variable
        String alphabet = "ABCD";

        // Display the string
        tv.setText("String : " + alphabet);

        // Convert the String to byte array
        byte[] bytesOfAlphabet = alphabet.getBytes();

        tv.setText(tv.getText() + "\nByte array (simple) : ");
        // Iterate over the byte array
        for(int i=0;i<bytesOfAlphabet.length;i++){
            tv.setText(tv.getText() +""+ bytesOfAlphabet[i] + ", ");
        }

        // Get the byte array from string using Charset
        byte[] byteArray = alphabet.getBytes(Charset.forName("UTF-8"));

        tv.setText(tv.getText() + "\nByte array (Charset UTF-8) : ");
        // Iterate over the byte array
        for(int i=0;i<byteArray.length;i++){
            tv.setText(tv.getText() +""+ byteArray[i] + ", ");
        }

        // Another way to convert string to byte array with Charset
        byte[] byteArrayUTF8 = alphabet.getBytes(StandardCharsets.UTF_8);

        tv.setText(tv.getText() + "\nByte array (StandardCharacters.UTF_8) : ");
        // Iterate over the byte array
        for(int i=0;i<byteArrayUTF8.length;i++){
            tv.setText(tv.getText() +""+ byteArrayUTF8[i] + ", ");
        }

        // Another way to convert a string to byte array
        // For this way we need to handle exception
        try{
            byte[] bytes = alphabet.getBytes("UTF-8");

            tv.setText(tv.getText() + "\nByte array (UTF-8): ");
            // Iterate over the byte array
            for(int i=0;i<bytes.length;i++){
                tv.setText(tv.getText() +""+ bytes[i] + ", ");
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
   }
}
More android examples