How to Watch Variables in Binary by using Visual Studio Debugger?

1 01 2009


In visual studio you can watch variable values in different formats. For instance, for viewing in hex add this to watch window – var,x and for octal – var,o. But its a pity that visual studio doesn’t support displaying variables in binaries. So how can you watch the value of a variable in binary, with debugger? 😉

watchvarinbinary_1
Image Courtesy – Pixdaus.


Well, we have to utilize the special feature of visual studio debugger. Basically the watch window is not just a tool to display the variable value. It can evaluate and execute small code snippets as well. If you add a function call to the watch window, that function will be called when debugger refreshes the watch values. So, all you have to do is – Add a global function which accepts integer value, converts it to binary string then display it to output window. Have a look at the function.

// Global function which converts integer to binary
// and dump to the output window.
void DumpBinary( DWORD Value )
{
    // Buffer to hold the converted string.
    TCHAR Buffer[255] = { 0 };

    // Convert the value to binary string.
    _itot( Value, Buffer, 2 );

    // Display to output window.
    CString csMessage;
    csMessage.Format( _T("\n%d in binary: %s"), Value, Buffer );
    OutputDebugString( csMessage );
}

Now if you want to convert the 100 to binary, break at some location and just add DumpBinary(100) to watch window and check the output in the output window. See the screenshot below.

watchvarinbinary


Just now I realized – how powerful the Visual Studio Debugger is. Hats off to Visual Studio Team!

Well, please note that in visual studio 2008 and may be in siblings, When you add this to watch window, its possible to see this error – “CXX0001: Error: error attempting to execute user function”. In that case just click the “Evaluate button” which appears next to it and the expression will be re-evaluate.

advancedseries
Targeted Audiance – Advanced.

Advertisements