PHP:以正整数计算' 1&#s;的二进制值

时间:2015-08-14 17:46:30

标签: php html html5

我想计算在0到65535之间的文本输入中有多少二进制文件

在代码中:变量$ a包含0到65535之间的正整数。

我在这里提供了一个解决方案。 什么是最好的解决方案? 请给我你的建议

的functions.php

    <?php
    require_once './config.php';

    /**
     * provides the number of "1" digits in the binary conversion of a decimal
     * number
     * @param int $a
     * @return int
     */
    function get_ones_from_binary_presentation_of_decimal($a) {
      if(!is_numeric($a)) {
        return false;
      }
      if($a < 0 OR $a > MAX_INT) {
        return -1;
      }
      $binary = decbin($a);
      $one_count = strlen(preg_replace('/0/', '', $binary));  
      return $one_count;
    }

    function get_ones($ones) {
      return ($ones == 1) ? "one" : "ones";
    }

    $basic_int = ($post['fromInt']) ? $post['fromInt'] : DECIMAL_NUMBER;
    $ones = get_ones_from_binary_presentation_of_decimal($basic_int);
    if (!$ones) {
      print '&quot;' . $basic_int . '&quot; is not a number.';
    }
    else if ($ones == -1) {
      print 'Please choose a number between 0 and 65535!';
    }
    else {
      print $basic_int . ' contains binary ' . $ones . ' ' . get_ones($ones);
    }

/**
 * sanitzes arrays recoursively like GET or POST
 */
function sanitize($elem) {
  if (!is_array($elem)) {
    $elem = htmlentities($elem, ENT_QUOTES, "UTF-8");
  } else {
    foreach ($elem as $key => $value) {
      $elem[$key] = sanitize($value);
    }
  }
  return $elem;
}

的index.php

<?php
  require_once './config.php';

  $post = sanitize($_POST);

  if ($post['submitted'] == 1) {
    $int = $post['fromInt'];
  }
  else {
    $int = DECIMAL_NUMBER;
  }


?>
<html>
  <head>
    <title>Binary ONEs</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="../css/frontend.css" />
  </head>
  <body>
    <form method="post" action="<?php print $_SERVER['PHP_SELF'] ?>">
      <label for="fromInt">Integer (bis 65.535): </label>
      <input id="fromInt" name="fromInt" size="5" value="<?php print $int ?>" />
      <input type="submit" name="submit" id="submit" value="Calculate" />
      <input type="hidden" name="submitted" value="1" />
    </form>
    <div id="out"><?php include 'functions.php'; ?></div>
  </body>
</html>

的config.php

<?php

// Decimal to binary number
define('DECIMAL_NUMBER', 21);

// integert-limit
define('MAX_INT', 65535);

1 个答案:

答案 0 :(得分:0)

您的问题是: 我想计算在0到65535之间的文本输入中有多少二进制'1'。(...)什么是最佳解决方案?请给我你的推荐

该问题的答案是:

echo substr_count(decbin(rand(0, 65535)), 1);

其中rand函数被您的已清理输入替换。

请注意,我没有接受您的清理程序,因为我认为您将使其适应您的代码。

如果不完全符合您的要求,请提供更多详细信息。

相关问题