Click here to Skip to main content
Licence GPL3
First Posted 28 Sep 2007
Views 15,963
Downloads 274
Bookmarked 10 times

Binary Clock for Windows Created Using C# in Visual Studtio 2008 Beta 2

By | 28 Sep 2007 | Article
A binary clock for Windows, created using C# in VS 2008 Beta 2. Implements decimal to binary conversion, ArrayLists, control arrays etc.

Introduction

This is a small Windows app which displays the current time in a binary way. It is built using Visual Studio 2008 Beta 2 and C#. I didn't aim to use any features specific to the .NET Framework 3.5 or VS 2008; however, involuntarily, I did use them - mostly having to do with the interface and debugging.

Background

While working on a project at work, I stumbled upon the JavaScript Tix clock. I found it neat and researched more. Then I saw the Binary clock. I decided to create this small binary clock of my own to serve the following purposes:

  1. Try Visual Studio 2008 while in a relaxed mode;
  2. Practice other fields of programming (I mostly work with ASP.NET and databases);
  3. Refresh C# in my head, for lately, most of my work is done in VB and JavaScript;
  4. Write a decimal to binary function which would leverage .NET;
  5. Have my very own binary clock "ticking" in the corner of the screen.

Using the Code

You can download the whole project, or just use the following code. The application consists of a simple Windows Form, which has only PictureBoxes on it named Hr10, Hr1 etc. The following is a code excerpt with the functions which make the clock (the rest is decor and the base requirements).

public partial class BinaryClock : Form
{

    //Colour variables used to switch patterns:
    private System.Drawing.Color colLit;
    private System.Drawing.Color colDim;
    private System.Drawing.Color colBackground;

    //the following 6 arrays will serve as Control Arrays:
    private System.Windows.Forms.PictureBox[] Hrs10;
    private System.Windows.Forms.PictureBox[] Hrs;
   
    private System.Windows.Forms.PictureBox[] Mns10;
    private System.Windows.Forms.PictureBox[] Mns;
    
    private System.Windows.Forms.PictureBox[] Scs10;
    private System.Windows.Forms.PictureBox[] Scs;

    public BinaryClock()
    {
        InitializeComponent();
    }

    private void BinaryClock_Load(object sender, EventArgs e) 
    {
        this.ColorPattern(this.mnuBlue.Name); //set it to the default colour pattern
        this.TransparencyKey = this.colBackground; //set the transparency

        //populate Control Arrays:    
        //put 10 hours LEDs into an array;
        Hrs10 = new System.Windows.Forms.PictureBox[] { hr20, hr10 };  

        // put Single hours into an array;
        Hrs = new System.Windows.Forms.PictureBox[] { hr8, hr4, hr2, hr1 }; 
        Mns10 = new System.Windows.Forms.PictureBox[] { mn40, mn20, mn10 };
        Mns = new System.Windows.Forms.PictureBox[] { mn8, mn4, mn2, mn1 };

        Scs10 = new System.Windows.Forms.PictureBox[] { sc40, sc20, sc10 };
        Scs = new System.Windows.Forms.PictureBox[] { sc8, sc4, sc2, sc1 };

        //thick the clock manually so there is no 1 sec delay on start; 
        timBinClock_Tick(sender, e);
        timBinClock.Start(); //start the clock;
    }
       
    private void timBinClock_Tick(object sender, EventArgs e)
    {
        //The timBinClock timer is set to tick every 1000 miliseconds = every 1 second
        int Foo; //this one is a Dummy
        
        //CONFIGURE HOURS:
        //(Note, we're using terms 10 and Singles 
        // as follows: in 14, the 10 is 1, and Single is is 4. 
        
        int HrNow = DateTime.Now.Hour; //get current hour
        //now get the 10 hours. 
        int TenHrNow = Math.DivRem(DateTime.Now.Hour, 10, out Foo) * 10;
        // translate the Single hours into binary;
        bool[] hrs = this.DecimalToBinary(HrNow - TenHrNow, 8);
        bool[] hrs10 = this.DecimalToBinary(TenHrNow / 10, 8);
        //translate the 10 hours into binary;

        LightOnOff(hrs10, this.Hrs10); //Light/Dim 10 hours LEDs
        LightOnOff(hrs, this.Hrs); //Light/Dim Single hours LEDs

        //CONFIGURE MINUTES:
        //Same deal as with the Hours above

        int MinNow = DateTime.Now.Minute;
        int TenMinNow = Math.DivRem(DateTime.Now.Minute, 10, out Foo) * 10;
        bool[] mns = this.DecimalToBinary(MinNow - TenMinNow, 8);
        bool[] mns10 = this.DecimalToBinary(TenMinNow / 10, 8);

        LightOnOff(mns10, this.Mns10);
        LightOnOff(mns, this.Mns);

        //CONFIGURE SECONDS:
        //Look above
        int SecNow = DateTime.Now.Second;
        int TenSecNow = Math.DivRem(DateTime.Now.Second, 10, out Foo) * 10;
        bool[] scs = this.DecimalToBinary(SecNow - TenSecNow, 8);
        bool[] scs10 = this.DecimalToBinary(TenSecNow / 10, 8);

        LightOnOff(scs10, this.Scs10);
        LightOnOff(scs, this.Scs);
    }

    private bool[] DecimalToBinary(int number, int MaxBit) 
    // Converts a decimal Number into a binary number, contained in 
    // array of integers;
    {
        
        //We use ArrayList here for flexibility sake; 
        System.Collections.ArrayList alBinaryNumber = 
                           new System.Collections.ArrayList();

        //since 1 is the lowest representation in the binary, we execute 
        // while our Max is no less than 1;
        while (MaxBit >= 1) 
        {
            // if the MaxBit consists in the Number
            // to be converted more than once 
            if (number / MaxBit > 0)
            {
                //if it's 1 then MaxBit is contained in the number 1 
                // time - put 1; and deduct the MaxBit from the number for 
                // we have recorded Max being there;
                alBinaryNumber.Add(true); 
                number = number - MaxBit;
            }
            else //if Max consists 0 times in the number:
            {
                alBinaryNumber.Add(false); //record 0;
            }
            MaxBit = MaxBit / 2;
            //Divide Max to descend one step 
            //in the binary system and continue; 
           
        }
        
        //after we went through all the steps, return ArrayList converted 
        // from ArrayList of objects into Array of booleans:
        return (bool[])alBinaryNumber.ToArray(typeof(bool));
    }

    private void LightOnOff(bool[] binNumber, System.Windows.Forms.PictureBox[] Lights)
    {
        //binNumber is the binary number represented in Array of booleans;
        //Lights is an array of PictureBox controls; 

        // in the For-Loop go through the binNumber array and "turn on" 
        // the corresponding "LED" lights in the Lights array:
        for (int i = (binNumber.Length - Lights.Length); 
             i - (binNumber.Length - Lights.Length) < Lights.Length; i++)
        {
            // since our binary number has 4 bins, while Lights aren't 
            // therefore we need to compensate for array length differences
            // therefore (binNumber.Length - Lights.Length)
            
            if (binNumber[i])//if "on"
            {
                //turn the light ON
                Lights.ElementAt(i - 
                 (binNumber.Length - Lights.Length)).BackColor = this.colLit; 
            }
            else 
            {
                //turn the light OFF
                Lights.ElementAt(i - 
                  (binNumber.Length - Lights.Length)).BackColor = this.colDim;
            }

            //It won't hurt to refresh the control since we are changing 
            // its colour;
            Lights.ElementAt(i - (binNumber.Length - Lights.Length)).Refresh(); 
        }
    }

Decimal to Binary

In the project itself, we use decimal to binary conversion, while specifying the maximum bit number. That is required for we need a fixed length byte. Below is a "pure" decimal to binary conversion where the maximum number of bits is calculated on the spot.

private bool[] DecimalToBinary(int number)
// Converts a decimal Number into a binary number,
// contained in array of integers;
{
    int MaxBit = 1; //This will be the maximum bit

    while (MaxBit <= (number / 2))
    //while our number doesn't fit into the construct increment MaxBit by 2. 
    {
        MaxBit = MaxBit * 2;
    }
    System.Collections.ArrayList alBinaryNumber = 
                       new System.Collections.ArrayList();
    //We use ArrayList here for flexibility sake; 

    while (MaxBit >= 1)
    //since 1 is the lowest representation in the binary,
    //we execute while our MaxBit is no less than 1;
    {
        if (number / MaxBit > 0)
        // if the MaxBit consists in the Number 
        // to be converted more than once 
        {
            //if it's 1 then MaxBit is contained in the number 1 time - put 1;
            alBinaryNumber.Add(true);
            number = number - MaxBit;
            // and decuct the MaxBit from the number
            // for we have recorded Max being there;
        }
        else //if Max consists 0 times in the number:
        {
            alBinaryNumber.Add(false); //record 0;
        }
        MaxBit = MaxBit / 2;
        //Divide Max to descend one step in the binary system and continue; 
    }
    //after we went through all the steps, return ArrayList 
    //converted from ArrayList of objects into Array of booleans:
    return (bool[])alBinaryNumber.ToArray(typeof(bool));
}

Points of Interest

  1. Uses Framework 3.5 and VS2008 - not particularly leveraging them, but still interesting. The Studio seems fine - actually enjoyed the interface and debugging. Despite the fact that it was Beta 2, I didn't encounter any major problems. There was a minor one: at a certain instance, the Solution Explorer stopped reacting on me pressing buttons which switch the view to form, to code etc... it's minor. Otherwise, I really liked the new Studio - it's the way to go.
  2. Implemented control array, i.e., created an array of controls which is much more flexible than in VB 6.
  3. Decimal to binary function uses an ArrayList which gets converted to an array of booleans - no rocket science, but neat and efficient. Some people use strings... while for this app it's not important, it is a good habit to avoid strings in such circumstances.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Alexei Fimine

Software Developer

Canada Canada

Member

"And though I have the gift of prophecy, and understand all mysteries, and all knowledge; and though I have all faith, so that I could remove mountains, and have not charity, I am nothing. And though I bestow all my goods to feed the poor, and though I give my body to be burned, and have not charity, it profiteth me nothing. Charity suffereth long, and is kind; charity envieth not; charity vaunteth not itself, is not puffed up, Doth not behave itself unseemly, seeketh not her own, is not easily provoked, thinketh no evil; Rejoiceth not in iniquity, but rejoiceth in the truth; Beareth all things, believeth all things, hopeth all things, endureth all things."

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralOk...but...why PinmvpMark Nischalke17:34 28 Sep '07  
AnswerRe: Ok...but...why PinmemberChebur15:20 29 Sep '07  
GeneralRe: Ok...but...why PinmvpMark Nischalke16:24 29 Sep '07  
GeneralRe: Ok...but...why PinmemberChebur17:01 29 Sep '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 28 Sep 2007
Article Copyright 2007 by Alexei Fimine
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid