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

我的目标是将十进制整数转换为二进制,如本视频中所述,http://youtu.be/XdZqk8BXPwg 使用php函数,我知道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);

我尝试在循环时,但我得到的结果颠倒了。


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


谢谢


陪伴而非守候
浏览 126回答 3
3回答

慕的地8271018

与其一次一个位地回显结果,不如通过在左侧添加新值来构建一个字符串:<?phpfunction decToBin($int) {&nbsp; &nbsp; $roundInt = intval($int) * 2;&nbsp; &nbsp; $output = '';&nbsp; &nbsp; while ($roundInt > 1) {&nbsp; &nbsp; &nbsp; &nbsp; $result = intval($roundInt = $roundInt / 2);&nbsp; &nbsp; &nbsp; &nbsp; if ($result % 2 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result = 0;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $output = $result . $output;&nbsp; &nbsp; }&nbsp; &nbsp; echo $output;}

鸿蒙传说

只是你在这里做错了几件事:您有一个舍入错误(使用intdiv进行整数除法,而不是您正在执行的操作,这会产生复合效应)。指定实际的类型隐藏而不是强制转换(确保类型安全)从函数返回实际值,不输出(保留对其最终组合的控制)以下是您的函数的实际外观...function decToBin(Int $int): String {&nbsp; &nbsp; $bin = ""; // Initialize the return value&nbsp; &nbsp; $roundInt = $int * 2;&nbsp; &nbsp; while ($roundInt > 1) {&nbsp; &nbsp; &nbsp; &nbsp; $roundInt = $result = intdiv($roundInt, 2); // Safe integer division&nbsp; &nbsp; &nbsp; &nbsp; $result &= 1;&nbsp; &nbsp; &nbsp; &nbsp; $bin = $result . $bin; // Compose with byte endianness at LSB first&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; return $bin;}var_dump(decToBin(123));现在您得到实际的正确结果...string(7) "1111011"

繁星点点滴滴

我对现有代码进行了最小的更改,而无需更改方法。您可以使用 strrev 函数来反转输出。这里,数据被附加到$return_data,它返回并存储在$returned_data中,然后使用strrev预定义函数。function decToBin($int) {$roundInt = intval($int) * 2;$return_data ='';&nbsp; &nbsp; while ($roundInt > 1) {&nbsp; &nbsp; &nbsp; &nbsp; $result = intval($roundInt = $roundInt / 2);&nbsp; &nbsp; &nbsp; &nbsp; if ($result % 2 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result = 0;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $return_data .=$result;&nbsp; //Data appending&nbsp; &nbsp; }&nbsp; return $return_data; //returns}$returned_data =&nbsp; decToBin(123);echo strrev($returned_data); //reverse function
打开App,查看更多内容
随时随地看视频慕课网APP