首页 > 解决方案 > 如何在php中反转while循环输出的顺序

问题描述

我的目标是使用 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

解决方案


与其一次一点地回显结果,不如通过在左侧添加新值来构建一个字符串:

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


推荐阅读