Binary clock

ddanbe 2 Tallied Votes 431 Views Share

Start a new console application and fill in the about 70 lines of code in the file. Run and enjoy!

Ab000dy_85 commented: I liked how you implemented the binary clock +2
thines01 commented: Good Stuff +13
using System;
using System.Text;
using System.Timers;

namespace ConsoleBinaryClock
{
    class Program 
    {
        private static DateTime Time;

        static void Main(string[] args)
        {
            Timer clock = new Timer(1000.0); // interval of one sec
            clock.Elapsed += new ElapsedEventHandler(OnClockTick);
            Console.WindowHeight = 5;
            Console.WindowWidth = 18;
            Console.Title = "Clock";
            DrawBlueBackground();
            Console.CursorVisible = false; 
            clock.Start();
            Console.ReadLine();
        }

        public static int ReadBit(int number, int BitPosition)
        {
            int i = number & (1 << BitPosition); //i=2^^Bitposition
            return (i > 0 ? 1 : 0);
        }

        private static string MakeDigitalString(string Head, int number)
        {
            string initialValue = " " + Head + " *  * ";
            StringBuilder sb = new StringBuilder(initialValue);
            for (int i = 0; i < 6; i++)
            {
                sb.Insert(5, ReadBit(number, i));
            }
            return sb.ToString();
        }

        private static void DrawBlueBackground()
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.WriteLine("bbbbbbbbbbbbbbbbbb");
            Console.WriteLine("bbbbbbbbbbbbbbbbbb");
            Console.WriteLine("bbbbbbbbbbbbbbbbbb");
            Console.WriteLine("bbbbbbbbbbbbbbbbbb");
            Console.Write("bbbbbbbbbbbbbbbbbb");
            Console.ResetColor();        
        }

        private static void OnClockTick(object source, ElapsedEventArgs e)
        {
            Time = DateTime.Now;
            string Hstr = MakeDigitalString("H", Time.Hour);
            string Mstr = MakeDigitalString("M", Time.Minute);
            string Sstr = MakeDigitalString("S", Time.Second);
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.SetCursorPosition(2, 1);
            Console.Write(Hstr);
            Console.SetCursorPosition(2, 2);
            Console.Write(Mstr);
            Console.SetCursorPosition(2, 3);
            Console.Write(Sstr);
        }
    }
}

Dani AI

Generated

Nice, compact console binary clock from . ’s GUI port and ’s background-loop suggestion show natural extension paths. Below are focused, practical improvements that make the console version more reliable, reduce flicker, and simplify the binary conversion without repeating the original code.

A simpler binary builder (MSB-first) is usually clearer than manual bit inserts:

static string ToBinaryFixed(int value, int bits = 6)
{
    return Convert.ToString(value, 2).PadLeft(bits, '0');
}

Reduce flicker by only redrawing rows that changed. Keep the previous string for each line and skip writes when equal:

static string prevH, prevM, prevS;

static void RenderRow(int y, string current, ref string prev)
{
    if (current == prev) return;
    Console.SetCursorPosition(2, y);
    Console.Write(current);
    prev = current;
}

Timer and sizing notes: System.Timers.Timer raises Elapsed on ThreadPool threads, which can interleave cursor operations. For a console clock prefer a single main-thread loop that sleeps until the next second boundary to keep output ordered (and to avoid cross-thread console writes):

while (true)
{
    var now = DateTime.Now;
    // build strings with ToBinaryFixed and call RenderRow(...)
    Thread.Sleep(1000 - now.Millisecond);
}

Setting Console window size can throw on constrained hosts; check Console.LargestWindowWidth/Height or wrap size calls in try/catch. For Forms/WPF ports (as explored), use UI timers (System.Windows.Forms.Timer or DispatcherTimer), bind bit state in WPF, and prefer event or Action callbacks for cross-class notifications — delegate wiring can be simplified with method-group assignment rather than explicit delegate construction.

Ab000dy_85 -3 Junior Poster in Training

Very nice,
Thank you for sharing

ddanbe 2,724 Professional Procrastinator Featured Poster

: Thank you. :) There is enough space left for improvement. Why not turn this into a forms or WPF application!

Ab000dy_85 -3 Junior Poster in Training

well after seen this I actually made the GUI based :/
I was so bored haha, but not as good as yours,, need improvements :D

Ab000dy_85 -3 Junior Poster in Training

here is what it looks like,
I just was very bored when I did it, because I wanna learn C#

I love C# and all, but I need to learn alot more,

I find Delegates, and events kinda hard to set up.
I kno how to use them but I cannot create them yet.

ddanbe 2,724 Professional Procrastinator Featured Poster

Nice :)
Did you know that line 14 of my code,
clock.Elapsed += new ElapsedEventHandler(OnClockTick);
is in fact a delegate attached to an event?
See more here:
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

Ab000dy_85 -3 Junior Poster in Training

yes, my main struggle is when I want another class call back a function in main form,
I have to set up a custom delegate,
I actually havent try to do it yet? but like 2 years ago I remember I was trying hard.
now different story I understand better, but need to try again, especially my project at work I am designing it from scratch through C# starting from sometime this week after I get all parts needed for the High level design done

StaubRein 0 Newbie Poster

nice snippet, but I would implement the background color with loops

ddanbe 2,724 Professional Procrastinator Featured Poster

: be my guest! Use this code as you see fit!
You could also implement a background like this:

class Program
    {
        static void Main(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.Cyan;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Clear();
            Console.WriteLine("Hello!");
            Console.ReadKey();
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.