Saturday, August 6, 2011

Binary Clock

For fun – yes, fun! – I coded a software clock that can display time in binary numbers. (My programs can get complex, so sometimes I write something simple just to unwind my brain – call it my way of doodling – and I know what you’re thinking: this guy needs to get a life. Well, to each his own.)

Below, the context menu (accessed by right-clicking the application window) shows the settings are 12 hour mode, decimal display, and display seconds.

 

Below, the clock is set to binary display with seconds off.

 

Background and text colors can be easily changed as seen below. Here, the display is set to 24 hour mode.

 

In the final picture, below, I kept 24 hour mode, changed to binary display, and turned seconds off. By chance, the time was 16:32 – both numbers being integer powers of ‘2’ and therefore represented by a ‘1’ followed by zeroes only.

Sometimes while writing a program I have to work out how to do something, and in this case I had to figure out how to convert an integer representing hours, minutes, or seconds into a textual representation of that integer expressed as a base 2 number. After some pondering, I came up with what I thought was a clever yet elegant algorithm to do that and wrapped it in a function. Here’s the result:

Private Function IntegerToBinaryString( _
                    
ByVal n As Integer) As String
    'determine the largest power of 2 that is smaller
    '
than the number "n"
    Dim txt As String = ""
    Dim d As Integer = n
    Dim exp As Integer = 0
    Do While d > 1
        d >>= 1
        exp += 1
    Loop
    'create a string that represents the number "n"
    'expressed as a base 2 number
    d = CInt(2 ^ exp)
    Do While d >= 1
        If n >= d Then
            txt &= "1"
            n -= d
        Else
            txt &= "0"
        End If
        d >>= 1
    Loop
    Return txt
End Function

It only converts positive integers, which is all I needed, but the conversion is fast. Give it the number 1 and it returns the text string “1”; give it the number 9 and it returns the text string “1001”; give it the number 59 and it returns the text string “111011”.

And as I patted myself on the back for creating such a cool little algorithm, I discovered that I needed only to have written this to accomplish the very same thing:

   Convert.ToString(n, 2)

A rookie mistake. A smart rookie, of course, but still, I should have known: before I try to figure out how to do something, I should first ask Google how to do it.

No comments: