hari s g
hari s g

Reputation: 63

How can i convert character to binary?

I'm an android self learner.I want to convert character to its corresponding binary.For example I'm giving the character 'A' (its ASCII is 65 and binary of 65 is 1000001) I want to get answer as 1000001. Thanks in advance..

Here is the my code

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Stack;

public  class MainActivity extends AppCompatActivity implements TextWatcher,View.OnClickListener
{
EditText txtDecimal;
TextView txtBinary;
Button btnAbout;
@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtDecimal=(EditText)findViewById(R.id.txtDecimal);
    txtBinary=(TextView)findViewById(R.id.txtval2);
    //txtdec=(TextView)findViewById(R.id.txtDecimal);
    txtDecimal.addTextChangedListener(this);
    btnAbout=(Button)findViewById(R.id.button1);
    btnAbout.setOnClickListener(this);
}
public void beforeTextChanged(CharSequence sequence,int start,int count,int after)
{
}
public void afterTextChanged(Editable editable)
{
}
public void onTextChanged(CharSequence sequence,int start,int before,int count) {
    calculate(2, txtBinary);        // for base 2 (binary)
}
public void calculate(int base,TextView txtView)
{
    if(txtDecimal.getText().toString().trim().length()==0)
    {
        txtView.setText("");
        return;
    }
    try
    {
        Stack<Object> stack=new Stack<Object>();
        int number=Integer.parseInt(txtDecimal.getText().toString());
        while (number>0)
        {
            int remainder=number%base; // find remainder
            if(remainder<10)
            // for remainder smaller than 10
            {
                stack.push(remainder);
                // push remainder in stack
            }

        number/=base;
    }
    StringBuffer buffer=new StringBuffer();
    while (!stack.isEmpty())
    {
        buffer.append(stack.pop().toString());
    }
    txtView.setText(buffer.toString());
}
catch (Exception e)
{
    txtView.setText(e.getMessage());
}
}

public void onClick(View view)
// to display Information in a dialog box
{
    // create a dialog box
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    // to allow cancelling the dialog box
    builder.setCancelable(true);
    // set title
    builder.setTitle("About NumberSystemConverter");
    // set message
    builder.setMessage("Made by HARI");
    // display dialog box
    builder.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
   }
 }

By this code i can convert only numbers.I want to convert characters too.By this code if I,m giving A it shows me that "invalid int a".I want to work both characters and numbers.plz help me...

Upvotes: 0

Views: 960

Answers (2)

Arshid KV
Arshid KV

Reputation: 10037

Try as follows

 String s = txtDecimal.getText().toString();  

    String binary_num ="";

          StringBuilder sb = new StringBuilder();
        String ascString = null;
        long asciiInt;
                for (int i = 0; i < s.length(); i++){
                    sb.append((int)s.charAt(i));
                    char c = s.charAt(i);
                }
                ascString = sb.toString();
                asciiInt = Long.parseLong(ascString);
                ascii_number =(int) intasciiInt;

            int binary[] = new int[ascii_number];
            int index = 0;
            while(ascii_number > 0){
                binary[index++] = ascii_number%2;
                ascii_number =  ascii_number/2;
            }
            for(int i = index-1;i >= 0;i--){
                binary_num = binary_num + binary[i];
            }
            txtBinary.setText(binary_num);

Upvotes: 2

Stephen C
Stephen C

Reputation: 718788

By this code i can convert only numbers.

That is incorrect. That code can also convert a character to "binary". Simply replace:

  int number=Integer.parseInt(txtDecimal.getText().toString());

with

  int number = (int) someCharacter;

and it will convert it.


Having said that, your code is not converting to binary at all. It is actually converting to a sequence of base-2 digits represented as a string. And if you use calculate) withbase` greater than 10, that string won't be decodable as base-N number.

Upvotes: 0

Related Questions