0

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...

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
hari s g
  • 53
  • 2
  • 13
  • 1
    what is your question? – njzk2 Apr 02 '16 at 03:25
  • @njzk2, he wants to convert from char to binary string. – Angel Koh Apr 02 '16 at 03:33
  • `Integer.parseInt(txtDecimal.getText().toString())` requires your input to be an integer. and even then, it would convert the integer value, not the value of the encoded representation of the number characters. you need to handle each character individually, and start by getting the integer value of each character. – njzk2 Apr 02 '16 at 03:36
  • 1
    convert character to ascii you can use int ascii = (int) character; and asccii to binary http://stackoverflow.com/a/917190/3790150 – saeed Apr 02 '16 at 03:48

2 Answers2

2

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);
Arshid KV
  • 9,631
  • 3
  • 35
  • 36
0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Instead of this int number = (int) someCharacter; I give like this int number=(int)txtDecimal.getText().toString(); It shows error.Plz help.. – hari s g Apr 02 '16 at 07:18
  • I thought you said that you wanted to convert a character. You seem to be trying to convert a string, not a character. – Stephen C Apr 02 '16 at 07:59
  • If I'm giving "h" it shows that "invalid int h".I think h is a character. Plz help... – hari s g Apr 02 '16 at 08:05
  • I don't understand what you are saying. Show me the actual code snippet you are talking about. – Stephen C Apr 02 '16 at 12:12
  • I'm talking about the above code.In that code .if i'm giving 4 it will show the output as 100.but if i'm giving h or any alphabet it will show the output as"invalid int "...plz help me to clear this.... – hari s g Apr 02 '16 at 16:12
  • Well if you are talking about this: `Integer.parseInt(txtDecimal.getText().toString())` ... it obviously won't work as a way to read a CHARACTER! You want something like this `txtDecimal.getText().charAt(0)` – Stephen C Apr 02 '16 at 16:18
  • But seriously, you >>ought<< to be reading the documentation for the classes that you are using. The information is all there to be read. – Stephen C Apr 02 '16 at 16:20
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108042/discussion-between-hari-s-g-and-stephen-c). – hari s g Apr 02 '16 at 16:27
  • ya it converts characters too..But an extra one appears with all characters.If i,m giving "a" it shows me that 1100001 and now it doesn't work for numbers.I want to work both the cases. plz correct the code... – hari s g Apr 03 '16 at 01:27
  • So you want to handle both numbers and characters? (You didn't say that before!) In that case, you need a heuristic to work out whether your `txtDecimal` contains a number or a character, and handle the two cases differently. – Stephen C Apr 03 '16 at 02:39
  • *"plz correct the code..."* - Nope. If I correct it for you, you won't learn about Java programming, and you won't learn how to communicate >>clearly<< with people about IT problems. StackOverflow should not be treated as a place where someone else will do the hard work of programming for you. If you want someone to work for you, pay them. There are lots of places to find "pay by the hour" or "pay by the task" prpgrammers. – Stephen C Apr 03 '16 at 02:42
  • ok..how to check txtDecimal contain a number or character?.I don't know much about android.I'm only a beginner...... – hari s g Apr 03 '16 at 06:45
  • Here a question for you: "1". Is that a number, or a character ... or both? – Stephen C Apr 03 '16 at 06:51
  • i want both(number and character) – hari s g Apr 03 '16 at 07:02