php - 如何在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
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;
}
推荐阅读
- c# - 在 OPC DA 服务器关闭事件期间调用数据更改事件以写入错误插件
- android - 有没有办法在 Android 的键盘后面滚动?
- postgresql - time.sleep() 在 plpythonu 中有 60 秒的限制?
- javascript - 购物车和来电显示/类别
- java - Android AGP 4.2.0 + Java 11 编译失败
- sql - 如何在 Oracle SQL 中查找过去 90 天内没有评论的帖子
- image-processing - OpenCV - 计算图像中两个边缘之间的距离
- windows - 32 位 COM 对象的 CoCreateInstance 不会在 Windows 10 64 位中返回
- c# - 使用泛型添加 HTTP 客户端 - ASP.NET Core
- scripting - 用 tcl 处理大文件