Java八进制到二进制转换(没有预定义方法)

时间:2015-11-26 09:01:53

标签: java string for-loop

我正在尝试创建一个将八进制值转换为二进制值的计算器。

temp = txt.getText();
temptemp = "";
if (prev == 3) {
    for (int i = 0; i < temp.length() - 1; i++) {
        if (temp.charAt(i) == '1') {
            temptemp = temptemp + "000";
        } else if (temp.charAt(i) == '2') {
            temptemp = temptemp + "001";
        } else if (temp.charAt(i) == '3') {
            temptemp = temptemp + "010";
        } else if (temp.charAt(i) == '4') {
            temptemp = temptemp + "011";
        } else if (temp.charAt(i) == '5') {
            temptemp = temptemp + "100";
        } else if (temp.charAt(i) == '6') {
            temptemp = temptemp + "101";
        } else if (temp.charAt(i) == '7') {
            temptemp = temptemp + "111";
        }
    }
    temp = temptemp;
    txt.setText(temp);

我的循环语句出了什么问题?请帮忙。谢谢:))

编辑:

我现在知道问题了。感谢所有的评论和答案。我以1增量离开了。我应该从== 0开始。对不起,谢谢你:))

5 个答案:

答案 0 :(得分:1)

您在转换表中犯了几个错误。 (没有0和没有7,错误的转换,通过过于停止循环来省略最后一个字符。)

更正后,您应该考虑使用StringBuilder而不是仅仅连接字符串!并且switch语句可能比if-else链

更具可读性
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < temp.length(); i++) {
    switch(temp.charAt(i)) {
    case '0':
        strBuilder.append("000");
        break;
    case '1':
        strBuilder.append("001");
        break;
    case '2':
        strBuilder.append("010");
        break;
    case '3':
        strBuilder.append("011");
        break;
    case '4':
        strBuilder.append("100");
        break;
    case '5':
        strBuilder.append("101");
        break;
    case '6':
        strBuilder.append("110");
        break;
    case '7':
        strBuilder.append("111");
        break;
    }
}
String temptemp = strBuilder.toString();

另一种可能性更短(并且完全不可读;)):

String[] convArray = { "000", "001", "010", "011", "100", "101", "110", "111" };
StringBuilder strBuild = new StringBuilder();
for (int i = 0; i < temp.length(); i++)
    strBuild.append(convArray[temp.charAt(i)-48]);
String temptemp = strBuild.toString();

请注意,只有String确实只包含数字0-7

时才会有效

答案 1 :(得分:1)

在不考虑所有8个分支的情况下很容易做到

for (int i = 0; i < temp.length(); i++) {
  int d = Character.getNumericValue(temp.charAt(i));                           
  for (int k=2; k >= 0; k--)
    temptemp = temptemp + Character.forDigit((i >> k) & 1, 2);
}

答案 2 :(得分:1)

您可以通过执行一些按位操作来跳过这个很长的明确案例列表:

StringBuilder sb = new StringBuilder(3 * temp.length());
for (int i = 0; i < temp.length(); i++) {
  // + check that the character is actually an octal digit.
  int digit = Character.digit(temp.charAt(i), 10);
  for (int b = 2; b >= 0; --b) {
    sb.append(Character.forDigit((digit >> b) & 0x1, 10));
  }
}

答案 3 :(得分:1)

\module\Admin\src\Admin\Controller\LoginController.php

class LoginController extends AbstractActionController
{
protected  $usersTable = null;

public function indexAction()
{
    return new ViewModel();
}

public function loginAction(){
    $form = new LoginForm();
    $form->get('submit')->setValue('Login');

    $request = $this->getRequest();
    if($request->isPost()){
        $login = new Login();
        $form->setInputFilter($login->getInputFilter());
        $form->setData($request->getPost());

        if($form->isValid()){
            $login->exchangeArray($form->getData());
            $this->getLoginDetails()->saveLoginForm($login);

            // Redirect to list of albums
            return $this->redirect()->toRoute('index');
        }

    }

    return array('form' => $form);
}
}

 \module\Admin\src\Admin\Form

 namespace Admin\Form;

 use Zend\Form\Form;

 class LoginForm extends Form
 {
 public function _construct()
 {

     parent::_construct('admin');

     $this->add(array(
         'name' => 'username',
         'type' => 'Text',
         'options' => array(
             'label' => 'Username',
             'id' => 'txtUsername',
         ),
     ));

     $this->add(array(
         'name' => 'password',
         'type' => 'password',
         'options' => array(
             'label' => 'Password',
             'id' => 'txtPassword',
         ),
     ));
     $this->add(array(
         'name' => 'submit',
         'type' => 'Submit',
         'attributes' => array(
             'value' => 'Login',
             'id' => 'btnSubmit',
         ),
     ));
 }
 }

\module\Admin\src\Admin\Model

namespace Admin\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Login implements InputFilterAwareInterface{

public $username;
public $password;
protected $inputFilter;

public function exchangeArray($data)
{
    $this->artist = (isset($data['username'])) ? $data['username'] : null;
    $this->title  = (isset($data['password']))  ? $data['password']  : null;
}

public function setInputFilter(InputFilterInterface $inputFilter){
    throw new \Exception("not used");
}

public function getInputFilter(){
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();

        $inputFilter->add(array(
            'name'     => 'username',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'min'      => 1,
                        'max'      => 50,
                    ),
                ),
            ),
        ));

        $inputFilter->add(array(
            'name'     => 'password',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'min'      => 1,
                        'max'      => 50,
                    ),
                ),
            ),
        ));

        $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
}

\module\Admin\view\admin\index
<?php


$form = $this->form;

$form->setAttribute('action', $this->url('admin', array('action' => 'login')));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('username'));
echo $this->formRow($form->get('password'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

echo $this->$form;

答案 4 :(得分:0)

对于你的情况,它是正确的转换。 您可以查看转换here

for (int i = 0; i < temp.length() - 1; i++) {
   if (temp.charAt(i) == '0') {
         temptemp = temptemp + "000";
   } else if (temp.charAt(i) == '1') {
        temptemp = temptemp + "001";
   } else if (temp.charAt(i) == '2') {
        temptemp = temptemp + "010";
   } else if (temp.charAt(i) == '3') {
        temptemp = temptemp + "011";
    } else if (temp.charAt(i) == '4') {
        temptemp = temptemp + "100";
    } else if (temp.charAt(i) == '5') {
        temptemp = temptemp + "101";
    } else if (temp.charAt(i) == '6') {
         temptemp = temptemp + "110";
    } else if (temp.charAt(i) == '7') {
        temptemp = temptemp + "111";
   }
}

相反,你可以循环遍历数字,每次将数字除以2,在循环内检查他的结果% 2(或使用>>)如果它0 {{ 1}},您将结果添加到数字0,否则添加1