Files
c3c/resources/examples/binarydigits.c3
Christoffer Lerno 43dc2d650c Use "String" consistently for "char[]" (#694)
Use "String" consistently for "char[]". Fix win32 return value.
2023-01-07 22:50:33 +01:00

25 lines
507 B
C

module binarydigits;
import std::math;
import std::io;
fn void main()
{
for (int i = 0; i < 20; i++)
{
VarString s = bin(i);
defer s.destroy();
io::printf("%s\n", s);
}
}
fn VarString bin(int x)
{
int bits = 1 + (int)(x == 0 ? 0 : math::log10((double)(x)) / math::log10(2));
VarString str;
str.append_repeat('0', bits);
for (int i = 0; i < bits; i++)
{
str.set((usz)(bits - i - 1), x & 1 ? '1' : '0');
x >>= 1;
}
return str;
}