如何将字符转换为二进制?

时间:2016-04-02 03:22:04

标签: java android

我是一个自我学习者。我想将角色转换为相应的二进制文件。例如,我给出了角色' A' (它的ASCII为65,二进制为65为1000001)我想得到答案为1000001。 提前谢谢..

这是我的代码

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);
   }
 }

通过这段代码,我只能转换数字。我也想转换字符。通过这段代码,如果我,我给它,它告诉我&#34;无效的一个&#34;。我想同时处理两个字符和numbers.plz帮助我...

2 个答案:

答案 0 :(得分:2)

尝试以下

 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);

答案 1 :(得分:0)

  

通过此代码,我只能转换数字。

这是不正确的。该代码还可以将字符转换为“二进制”。只需更换:

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

  int number = (int) someCharacter;

它将转换它。

话虽如此,您的代码根本没有转换为二进制文件。它实际上是转换为表示为字符串的base-2数字序列。如果你使用大于10的calculate) with base`,那么该字符串将不能作为base-N数字解码。