繁体   English   中英

如何反转php中while循环输出的顺序

[英]How to inverse the order of a while loop output in php

我的目标是使用 php 函数将十进制整数转换为二进制,如本视频http://youtu.be/XdZqk8BXPwg中所述,我知道 php 可以使用内置的 decbin() 开箱即用,但我反正想写一篇。

<?php

function decToBin($int) {
$roundInt = intval($int) * 2;
    while ($roundInt > 1) {
        $result = intval($roundInt = $roundInt / 2);
        if ($result % 2 == 0) {
            $result = 0;
        } else {
            $result = 1;
        }
        echo $result;
    }
}
decToBin(123);

我尝试了 while 循环,但结果颠倒了。

有没有办法可以反转它,所以我得到 01111011 而不是 11011110,或者在前面没有零的情况下更好。

谢谢

通过在左侧添加新值来构建一个字符串,而不是一次一位地回显结果:

<?php
function decToBin($int) {
    $roundInt = intval($int) * 2;
    $output = '';
    while ($roundInt > 1) {
        $result = intval($roundInt = $roundInt / 2);
        if ($result % 2 == 0) {
            $result = 0;
        } else {
            $result = 1;
        }
        $output = $result . $output;
    }
    echo $output;
}

你在这里做错了几件事:

  1. 您有一个舍入错误(使用intdiv进行整数除法,而不是您正在执行的操作,这具有复合效果)。

  2. 指定实际的类型提示而不是强制转换(确保类型安全)

  3. 从函数返回一个实际值,不要输出(您保留对其最终组合的控制权)

这是您的功能实际上应该是什么样子......

function decToBin(Int $int): String {
    $bin = ""; // Initialize the return value

    $roundInt = $int * 2;

    while ($roundInt > 1) {
        $roundInt = $result = intdiv($roundInt, 2); // Safe integer division
        $result &= 1;
        $bin = $result . $bin; // Compose with byte endianness at LSB first  
    }

    return $bin;
}

var_dump(decToBin(123));

现在你得到了实际正确的结果......

string(7) "1111011"

我在不更改方法的情况下对现有代码进行了最少的更改。 您可以使用strrev函数来反转输出。 这里数据附加到 $return_data ,它返回并存储在 $returned_data 中,然后使用 strrev 预定义函数。

function decToBin($int) {
$roundInt = intval($int) * 2;
$return_data ='';
    while ($roundInt > 1) {
        $result = intval($roundInt = $roundInt / 2);
        if ($result % 2 == 0) {
            $result = 0;
        } else {
            $result = 1;
        }
        $return_data .=$result;  //Data appending
    }
  return $return_data; //returns
}
$returned_data =  decToBin(123);
echo strrev($returned_data); //reverse function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM