Yesterday during lunch break I thought about building a binary clock with an ESP32. Since I don’t have a corresponding development environment on my device, I quickly prescribed the function for converting the time into a binary string in Powershell. The next step then is to convert this code into a C function.

The simplest variant is:

[Convert]::ToString (64,2)

However, this logic would not run on an ESP32. Therefore a function that can be easily converted to C later has to be found.

function Convert-ToBinaryString
{
    param(
	 [Parameter(Mandatory=$true)]
     [int]$start,
	 [Parameter(Mandatory=$true)]
     [int]$value
    )
	
    $binary = "";

    while($start -gt 0)
    {
        if($value / $start -ge 1)
        {
            $binary += "1";
            $value = $value - $start;
        }
        else
        {
            $binary += "0";
        }

        $start = $start -shr 1;
    }

    return $binary;
}

A quick example to check that the function works.

# example
Convert-ToBinaryString -start 32 -value 22
"--"
Convert-ToBinaryString -start 32 -value 45

Output
010110

101101

Now the C/C++-Code

#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;

string ConvertToBinaryString(int start, int value)
{

    string binary = "";

    while (start > 0)
    {
        if (value != 0)
        {
            if (value / start >= 1)
            {
                binary += "1";
                value = value - start;

            }
            else
            {
                binary += "0";
            }

            
        }
        else if (value == 0)
        {
            binary += "0";
        }
        start = start >> 1;
    }

    return binary;
}

int main()
{
    string test = ConvertToBinaryString(16, 8);
    cout << test;
    getchar();
    return 0;
}