Windows 7 .NET Interop Sample Libraries

We’ve got .NET sample libraries and example for managed code developers to target Windows 7 new APIs!

The Windows 7 Beta SDK is a great source of documentation and examples for using these new sets of APIs. However, most of the examples are written in native code similar to Windows 7 APIs which are all native C, C++, and COM APIs, which makes the life of managed code developers a bit hard. For that reason, Microsoft created the Windows Vista Bridge project that makes it easier for managed code developers to use Windows OS-specific APIs such as those described above.

The current version of the Window Vista Bridge, version 1.4 contains many useful “Windows Vista” features such as  Restart and Recovery, Search, Power Awareness and other Shell integrations. However the current version doesn’t include any Windows 7 features. It will support key Windows 7 APIs in the near future, but until then, we have developed an intermediate set of solutions for supporting managed code developers who wish to target Windows 7 Beta today and not wait for the time the Windows API Code Pack for the .NET Library (the new name of Windows Vista Bridge) will be available.

With that caveat in place, we can go ahead and introduce some new managed code wrappers that will allow managed code developers to use the Windows 7 Taskbar, manipulate Libraries, add Multi-Touch support for WinForms or WPF 3.5 SP1, and enable Sensors and Location in their applications.


The Taskbar Sample .NET Interop Library allows developers to:

  • Create and manipulate JumpLists including tasks and items
  • Display Dynamic Overlay Icons, Thumbnail Toolbars
  • Use the Taskbar progress bar
  • Control Custom Thumbnail Preview, and custom Preview also known as – AeroPeek

The Windows 7 Taskbar Sample .NET Interop Library is available for download and include 4 demos showcasing all the Taskbar features.


Libraries are new in Windows 7 and provide a logical representation of the user’s data on  his local computer and on remote computers. With Libraries, the user can define which physical folders are mapped to which library and achieve better search quality and easier “maintenance” of his content. In Windows 7, it is important for developers to

enable their applications to become Library-aware by supporting Libraries. This will integrate the user’s application and Windows experiences and maintain the integrity of your applications in various scenarios

The Windows 7 Library Sample .NET Interop Library allows developers to:

  • Manipulate and control the libraries in Windows 7 including create a new library or delete an existing one
  • Add or remove physical locations to a Library
  • Set an icon for each library
  • Enumerate the contents of a given library’s physical location (the actual folders) to track down and map all the items in that library

Read more at the new Windows 7 Blog for Developers

Source- Tech Today

Refactoring: Magic Numbers

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Another type of refactoring patterns is the Magic Number pattern.

Magic numbers are numbers with special meaning and value that usually are not obvious, such as PI. They are really nasty when you need to reference the same number many times. If the number might ever change, making the change is a nightmare. Even if you don’t make a change, you have the difficulty of figuring out what is going on.

If you have a magic number into your code and you use it frequently, you can create a constant, name it after the meaning, and replace the number with it. Most languages support constants. There is no cost in performance and there is a great improvement in readability.

But, before you do this refactoring, you should always look for an alternative. Look at how the magic number is used. Often you can find a better way to use it. If the magic number is a type code, consider replace type code with a class. If the magic number is the length of an array, use anArray.length instead when you are looping through the array. Otherwise, you can go and create your constant.

For example, the following code converts between meters and feet, and it uses a magic number that’s the feet in one meter:

// C# Code

public static double ConvertMetersToFeet(double meters)
    return meters * 3.2808398950131233595800524934383;
public static double ConvertFeetToMeters(double feet)
    return feet / 3.2808398950131233595800524934383;
' VB.NET Code

Public Function ConvertMetersToFeet(meters As Double) As Double
    Return meters * 3.2808398950131233595800524934383
End Function

Public Function ConvertFeetToMeters(feet As Double) As Double
    Return feet / 3.2808398950131233595800524934383
End Function

So, we can refactor the code to be:

// C# Code

public const double MeterFeet = 3.2808398950131233595800524934383;

public static double ConvertMetersToFeet(double meters)
    return meters * MeterFeet;
public static double ConvertFeetToMeters(double feet)
    return feet / MeterFeet;
' VB.NET Code

Public Const MeterFeet As Double _
    = 3.2808398950131233595800524934383

Public Function ConvertMetersToFeet(meters As Double) As Double
    return meters * MeterFeet
End Function

Public Function ConvertFeetToMeters(feet As Double) As Double
    return feet / MeterFeet
End Function

The lesson quoted from the book “Refactoring: Improving the Design of Existing Code” by Martin Fowler. Code snippets by Just Like a Magic.

Programmatically Compress and Decompress Files

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

This lesson is very easy. This lesson focuses on how to compress and decompress files programmatically using .NET Framework and C# -or any language that supports .NET of course.

Currently .NET Framework supports two types of compression algorithms:

  • Deflate
    This is a very simple algorithm, used for simple compression and decompression operations. Don’t use this algorithm except if you intend to use compressed data only in your application because this algorithm is not compatible with any compression tool.
  • GZIP
    This algorithm uses internally the Deflate algorithm. This algorithm includes a cyclic redundancy check value for detecting data corruption. Also it’s compatible with most compression tools because it writes headers to the compressed file, so compression tools -like WinZip and WinRAR- can easily access the compressed file and decompress it as well. This algorithm also can be extended to use other algorithms internally other than Deflate.

For a complete GZIP reference see RFC 1952 (GZIP File Format Specification).

The most powerful compression tool now is WinRAR.

Fortunately, whether using Deflate or GZIP in .NET, code is the same; the only thing that needs to change is the class name.

Deflate and GZIP can be found in the namespace System.IO.Compression that resides on assembly System.dll. This namespace contains only three types, the two algorithms implementation classes DeflateStream and GZipStream -both inherit directly from System.IO.Stream class-, and an enumeration CompressionMode that defines the operation (compression or decompression).

Compressing a file

The code for compression is very simple:

Code snippets in this lesson rely on the fact that you added two using (Imports in VB) statements, System.IO and System.IO.Compression.

// C# Code

string fileToBeCompressed = "D:\My Great Word Document.doc";
string zipFilename = "D:\";

using (FileStream target = new FileStream(zipFilename, FileMode.Create, FileAccess.Write))
using (GZipStream alg = new GZipStream(target, CompressionMode.Compress))
    byte[] data = File.ReadAllBytes(fileToBeCompressed);
    alg.Write(data, 0, data.Length);

Code explanation:
If you are going to compress a file then you must specify the CompressionMode.Compress option, and also you must specify a Stream that will the data be written to.
After creating the class you can compress the data by using its Write() method.

If you intended to use the Deflate algorithm, just change the class name to DeflateStream.

Decompressing a file

The code that decompresses a compressed file is very similar:

// C# Code

string compressedFile = "D:\";
string originalFileName = "D:\My Great Word Document.doc";

using (FileStream zipFile = new FileStream(compressedFile, FileMode.Open, FileAccess.Read))
using (FileStream originalFile = new FileStream(originalFileName, FileMode.Create, FileAccess.Write))
using (GZipStream alg = new GZipStream(zipFile, CompressionMode.Decompress))
    while (true)
        // Reading 100bytes by 100bytes
        byte[] buffer = new byte[100];
        // The Read() method returns the number of bytes read
        int bytesRead = alg.Read(buffer, 0, buffer.Length);

        originalFile.Write(buffer, 0, returnedBytes);

        if (bytesRead != buffer.Length)
' VB.NET Code

Dim compressedFile As String = ""
Dim originalFileName As String = "D:My Great Word Document.doc"

Dim zipFile As New FileStream(compressedFile, FileMode.Open, FileAccess.Read)
Dim originalFile As New FileStream(originalFileName, FileMode.Create, FileAccess.Write)
Dim alg As New GZipStream(zipFile, CompressionMode.Decompress)

While (True)
    ' Reading 100bytes by 100bytes
    Dim buffer(100) As Byte

    ' The Read() method returns the number of bytes read
    Dim bytesRead As Integer = alg.Read(buffer, 0, buffer.Length)

    originalFile.Write(buffer, 0, bytesRead)

    If (bytesRead  buffer.Length) Then
        Exit While
    End If
End While

Code explanation:

First, we create a file stream to read the ZIP file, and then we created our algorithm class that encapsulates the file stream for decompressing it.

Then we created a file stream for the original file, for writing the decompressed data.
After that, we read the data compressed 100bytes after each other -you may prefer more- and write this data to the original file stream.

By encapsulating disposable objects into using statements you become assured that every object will be disposed in a certain point -end of the using statement- and no object will retain in memory.

Try it yourself

Develop a simple application that can be used to compress and decompress files.

This application can compress several files into one file and decompress them as well.

Besides algorithms classes you may use System.IO.BinaryWriter and System.IO.BinaryReader to get full control of how the file contents will be.

DirectX 9.26.1590 (March 2009), End-User Runtime and Developers SDK

The March 2009 DirectX SDK download contains the tools needed to build cutting-edge, media-rich, interactive applications. It includes runtimes, headers and libraries, samples, documentation, utilities, and support for C++ development.

The March SDK also includes an update to the Technical Preview for Direct3D 11, the latest version of Direct3D that provides support for tessellation and general purpose GPU processing, as well as the Technical Preview for Direct2D and DirectWrite, the new Windows APIs for accelerated 2D rendering and font and text rendering. Further changes in the March SDK include improvements to the audio tools and the new XNA Math library.

Source- Tech Today

Enumerating SQL Server Instances

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Starting from version 2.0, .NET supports a mechanism to enumerate the SQL Server instances in the local network. This is done by System.Sql.SqlDataSourceEnumerator class that resides on the assembly System.Data.

This class is a implements the singleton pattern, means that you can not instantiate it, and only a single instances serves all, accessed via the static property Instance.

Using the GetDataSources method of SqlDataSourceEnumerator, you get a DataTable object that contains four columns, ServerName, InstanceName, IsCulstered, and Version (Clear names, right?)

The following code retrieves information about all visible SQL Server instances in the local network:

// C# Code

static void Main()
    DataTable table =


private static void DisplayTable(DataTable table)
    foreach (DataRow row in table.Rows)
        foreach (DataColumn col in table.Columns)
            Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
        Console.WriteLine(new string(' ', 30));
 ' VB.NET Code

Sub Main()
    Dim table As DataTable = SqlDataSourceEnumerator.Instance.GetDataSources()

End Sub

Sub DisplayTable(ByVal table As DataTable)
    For Each row As DataRow In table.Rows
        For Each col As DataColumn In table.Columns
            Console.WriteLine("{0} = {1}", col.ColumnName, row(col))
            Console.WriteLine(New String(" "c, 30))
End Sub

If you have a firewall installed on your machine, you will be asked to give permissions to the application.

GetDataSources() demands the FullTrust permission set.

Due to the nature of the mechanism used by SqlDataSourceEnumerator to locate data sources on a network, the method will not always return a complete list of the available servers, and the list might not be the same on every call.

Microsoft Code Analysis Tool .NET (CAT.NET) v1

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.

CAT.NET is a snap-in to the Visual Studio IDE that helps you identify security flaws within a managed code (C#, Visual Basic .NET, J#) application you are developing. It does so by scanning the binary and/or assembly of the application, and tracing the data flow among its statements, methods, and assemblies. This includes indirect data types such as property assignments and instance tainting operations. The engine works by reading the target assembly and all reference assemblies used in the application — module-by-module — and then analyzing all of the methods contained within each. It finally displays the issues its finds in a list that you can use to jump directly to the places in your application’s source code where those issues were found. The following rules are currently support by this version of the tool. – Cross Site Scripting – SQL Injection – Process Command Injection – File Canonicalization – Exception Information – LDAP Injection – XPATH Injection – Redirection to User Controlled Site

Download Now

Working with SQL Server BLOB Data in .NET

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.


Binary Large Objects (BLOBs) are pieces of data that have -usually- exceptionally large size (such as pictures or audio tracks). These values stored in SQL Server in an image column.

Sometimes the term BLOB is also applied to large character data values, such as those stored in text or ntext columns.

Also you can store BLOB data in a binary column, but it doesn’t take larger than 8000 bytes. And image columns are more flexible.

Working with BLOB data is a bit strange because:

  1. You don’t know how much size will be the retrieved data.
  2. The data may be very large so we need to retrieve it in chunks.

Our example is fairly simple. This example stores files in a database (FileStore) and retrieves it by name. The example relies on a database that contains one table, MyFiles. And the table itself contains two columns one for filename (PK) and the other is an image column for the file itself.

Storing BLOB data

Storing BLOB data in a database is easiest part:

In order to run this code, you must add using statements to Sql.Data.SqlClient and System.IO.

// C# Code

static void StoreFile(string filename)
    SqlConnection connection = new SqlConnection
        ("Server=(local) ; " +
        "Initial Catalog = FileStore ; " +
        "Integrated Security = SSPI");

    SqlCommand command = new SqlCommand
        ("INSERT INTO MyFiles VALUES (@Filename, @Data)",




' VB.NET Code

Sub StoreFile(ByVal filename As String)
    Dim connection As New SqlConnection( _
        "Server=(local) ; Initial Catalog = FileStore ; " & _
        "Integrated Security = SSPI")

    Dim command As New SqlCommand( _
        "INSERT INTO MyFiles VALUES " & _
        "(@Filename, @Data)", connection)

    command.Parameters.AddWithValue("@Filename", _
    command.Parameters.AddWithValue("@Data", _



End Sub

Code explanation:
First, we created a connection to the SQL Server database. And then, we created the SqlCommand object that will hold the T-SQL Insert statement. After that, we filled the command parameters with required values. Finally, we executed the command.

Well, for avoiding SQL-Injection attacks, it’s recommended that you use parameters instead of hard-coding the argument. Moreover, you can’t represent binary values as strings.
Frankly, it’s recommended using stored procedures instead of coding the commands.

It’s highly recommended that you dispose disposable objects like SqlConnection and SqlCommand. Try encapsulating it in a using statement.

Retrieving BLOB data

Retrieving BLOB data is a bit complex than storing it. The following method demonstrates this:

// C# Code

static byte[] RetrieveFile(string filename)
    SqlConnection connection = new SqlConnection
        ("Server=(local) ; Initial Catalog = FileStore ; Integrated Security = SSPI");

    SqlCommand command = new SqlCommand
        ("SELECT * FROM MyFiles WHERE Filename=@Filename", connection);

    command.Parameters.AddWithValue("@Filename", filename);


    SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);


    MemoryStream memory = new MemoryStream();

    long startIndex = 0;
    const int ChunkSize = 256;
    while (true)
        byte[] buffer = new byte[ChunkSize];

        long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize);

        memory.Write(buffer, 0, (int)retrievedBytes);

        startIndex += retrievedBytes;

        if (retrievedBytes != ChunkSize)


    byte[] data = memory.ToArray();


    return data;
' VB.NET Code
Function RetrieveFile(ByVal filename As String) As Byte()
    Dim connection As New SqlConnection( _
        "Server=(local) ; Initial Catalog = FileStore ; " & _
        "Integrated Security = SSPI")

    Dim command As New SqlCommand( _
        "SELECT * FROM MyFiles " & _
        "WHERE Filename=@Filename", connection)

    command.Parameters.AddWithValue("@Filename", filename)


    Dim reader As SqlDataReader = command.ExecuteReader _


    Dim memory As New MemoryStream()

    Dim startIndex As Long = 0
    Const ChunkSize As Integer = 256
    While (True)
        Dim buffer(ChunkSize) As Byte

        Dim retrievedBytes As Long = _
            reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)

        memory.Write(buffer, 0, CInt(retrievedBytes))

        startIndex += retrievedBytes

        If (retrievedBytes  ChunkSize) Then
            Exit While
        End If
    End While


    Dim data() As Byte = memory.ToArray()


    Return data
End Function

Code explanation:
After connecting to the database and writing our query, we executed the query by calling ExecuteReader() method of the command object to get read-only forward-only pointer to the retrieved rows.

By default, SqlDataReader reads entire rows -that can be gigabytes of data.- By specifying CommandBehavior.SequentialAccess, it reads the data sequentially in a given chunk size by calling the GetBytes() -or GetChars for BLOB textual data- method.

Calling Read() of the SqlDataReader objects advances the pointer to the next row which is the first single row -if found- in our example.

The GetBytes() method takes five arguments:

  1. The column index.
  2. The index of which to start reading.
  3. The buffer object that will keep current retrieved data.
  4. Index in buffer of which to begin writing t.
  5. The length (chunk size) of the data to retrieve.

It it worth mentioning that this method returns number of bytes retrieved. After calling this method we used a MemoryStream object to write all data retrieved to.

Finally, we retrieve data by calling MemoryStream’s ToArray() function. (I think the code is now clear)

It’s not recommended using MemoryStream if the data is very huge.

SqlConnection, SqlCommand, SqlDataReader, and MemoryStream are all disposable objects.
Because the MemoryStream object may contain the retrieved data it’s highly recommended that you dispose it as soon as possible.

For a complete example download the sample project FileStore.
This project uses a database for storing files and retrieving it.
This database contains only one table, its definition is as follows:

FileStore File Table Definition

For creating the database, the project also inculdes a SQL Query file that contains the commands for creating it. Simply execute the file.

Download Here

Programmatically Swapping Mouse Buttons

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Swapping mouse buttons means swapping the two buttons, making the right button acts like the left one and vice versa. This is done -for normal users of course- using the Mouse properties dialog in the control panel. See the next figure.

For we developers you need to do this programmatically, and this is done by a very very trivial -not a joke- Win32 API function, SwapMouseButton (resides on user32.dll). The syntax of the function -in C- is as follows:

BOOL SwapMouseButton(
    BOOL fSwap

This function simply takes a single BOOL argument and returns a BOOL value too.

If fSwap is TRUE then the right mouse button will do the primary functions like the left button -by default- does, and the left button will do the secondary functions that the right button -by default- does.

If the function swapped the buttons, then it will return FALSE, otherwise TRUE.

BOOL can take one of values TRUE (non-zero) or FALSE (zero).

In .NET Framework, you need to write a wrapper to this API function and this wrapper is like this:

// C# Code
static extern bool SwapMouseButton(bool fSwap);
Declare Auto Function SwapMouseButton Lib "user32.dll" _
    (ByVal fSwap As Boolean) As Boolean

The DllImport attribute defines the DLL that contains the function.

The MarshalAs attributes defines how .NET types will be mapped to Win32 types (this process called marshaling). We applied this attribute to the return value of the function and to the single argument of the function.

The static extern modifiers are required for any PInvoke function.

PInvoke stands for Platform Invokation. It’s the process of wrapping an API function to .NET code.

Marshaling is the process of creating a bridge between .NET types and unmanaged types.

For unmanaged BOOL, .NET makes the marshaling process automatically, so you can safely remove the MarshalAsAttribute attributes.

Now it’s the time for the code for calling the function.

// C# Code

public void MakeRightButtonPrimary()

public void MakeLeftButtonPrimary()
' VB.NET Code

Public Sub MakeRightButtonPrimary()
End Sub

Public Sub MakeLeftButtonPrimary()
End Sub

Retrieving Motherboard Serial Number using WMI

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

A simple way to get system information is through Windows Management Instrumentation (WMI).

WMI was firstly introduced part of Windows 2000. It’s designed to help your system, applications, and networks.

WMI has amazing design; It’s implemented like a large database that contains several tables and types. And you can query it using SQL statements (really!).

.NET Framework includes a various classes for dealing with WMI. These classes reside on assembly System.Management that you can reference it into your project.

Querying WMI is very simple. First, create a ManagementObjectSearcher object that will hold the SQL query. Then you execute the query by calling the Get() method of the ManagementObjectSearcher object, returns a collection of ManagementObject objects. These object looks like rows in a database that you can access its columns -PropertyData objects- and retrieve its values.

In WMI tables called classes, rows called objects, and columns called properties.

The following example demonstrates how to get Motherboard information like its name and serial number:

// C# Code

// First we create the ManagementObjectSearcher that
// will hold the query used.
// The class Win32_BaseBoard (you can say table)
// contains the Motherboard information.
// We are querying about the properties (columns)
// Product and SerialNumber.
// You can replace these properties by
// an asterisk (*) to get all properties (columns).
ManagementObjectSearcher searcher =
    new ManagementObjectSearcher
    ("SELECT Product, SerialNumber FROM Win32_BaseBoard");

// Executing the query...
// Because the machine has a single Motherborad,
// then a single object (row) returned.
ManagementObjectCollection information = searcher.Get();
foreach (ManagementObject obj in information)
    // Retrieving the properties (columns)
    // Writing column name then its value
    foreach (PropertyData data in obj.Properties)
        Console.WriteLine("{0} = {1}", data.Name, data.Value);

// For typical use of disposable objects
// enclose it in a using statement instead.
' VB.NET Code

' First we create the ManagementObjectSearcher that
' will hold the query used.
' The class Win32_BaseBoard (you can say table)
' contains the Motherboard information.
' We are querying about the properties (columns)
' Product and SerialNumber.
' You can replace these properties by
' an asterisk (*) to get all properties (columns).
Dim searcher As New ManagementObjectSearcher _
    ("SELECT Product, SerialNumber FROM Win32_BaseBoard")

' Executing the query...
' Because the machine has a single Motherborad,
' then a single object (row) returned.
Dim information As ManagementObjectCollection = searcher.Get()
For Each obj As ManagementObject In information
' Retrieving the properties (columns)
' Writing column name then its value
    For Each data As PropertyData In obj.Properties
        Console.WriteLine("{0} = {1}", data.Name, data.Value)

' For typical use of disposable objects
' enclose it in a using statement instead.
' VB6
Set colProcessList = GetObject("Winmgmts:") _
    .ExecQuery("SELECT SerialNumber, Product FROM Win32_BaseBoard")

For Each objprocess In colProcessList
    MsgBox ("Serial Number=" & objprocess.SerialNumber)
    MsgBox ("Product=" & objprocess.Product)

To read more about WMI and get lists of classes and features that it supports, see WMI Reference.

A long time ago, I used that mechanism to protect my application from copying it from a PC to another. The application asks the user for the serial number if he changed his PC (frankly, Motherboard). Did you validate? The serial number itself is an encrypted hash of the Motherboard serial number!

Converting between color decimal and hexadecimal representation

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.


Contents of this article:

  • Contents
  • Introduction
  • Color Represenatation
  • Converting Decimal to Hexadecimal
  • Converting Hexadecimal to Decimal
  • Try it Yourself


Before we begin our article we need to know first what is decimal and what is hexadecimal.

Using decimal representation means using base-10 representation of numbers which means that every digit of the number can be one of 10 values, 0 through 9.

A good example is 195. It’s is 3 digits and every digit is between 0 and 9.

On the other hand, hexadecimal is base-16 representation which means that there are 16 of base values that every digit in the number can be one of. These base values are 0 through 9 and A through F. From 0 to 9 are the same in dec (the shorthand for decimal). A equals 10, B equals 11, C equals 12, etc.

An example is 14 (decimal). If we need to represent it in hexadecimal we can say D.

Another good example is 9 (decimal). If we need to represent it in hex (the shorthand for hexadecimal,) you can say 9 too.

Color representation

You already know that a colors consists of 3 values; RGB (Red, Green and Blue). Although, there’re times when we blend it with another value (Alpha) to make color transparent, however it is not common. So we end up with 4 values (ARGB) to represent our color. True? Every value of these four occupies a single byte in memory so every value ranges from 0 to 255.

In HTML for instance you can represent any color by its name (if it is a known color like Red) or by combining the RGB values using hexadecimal (HTML doesn’t support Alpha.) You cannot use decimal values to represent colors in HTML. So you need to know how to convert between every decimal value to its equivalent hexadecimal and vice versa.

Converting decimal to hexadecimal

You already know that decimal values from 0 to 15 have the hex counterparts 0 through 9 and A through F so conversion will be very easy in this range. For a decimal value greater than 15 you need to apply a simple formula to convert it.

  1. First, divide the value by 16 (because hex is base-16), then add the hex result (e.g. A for 10) to the left.
  2. Second, divide the value by 16, and then add the remainder (modulus) to the right of the last number.


- 11 (dec)
11 = B
Result = B (hex)

- 160 (dec)
160 / 16 = 10
160 mod 16 = 0
10 = A
0 = 0
Result: A0 (hex)

- 254 (dec)
254 / 16 = 15
254 mod 16 = 14
15 = F
14 = E
Result = FE (hex)

Because every value of ARGB occupies a single byte, then the values range from 0 to 255 so in hexadecimal they range from 0 to FF!

Converting hexadecimal to decimal

For hex values from 0 through 9 and A through F, they have equivalents in decimal.

For values greater than F (15) all you need is to reverse the steps you did in converting decimal to hex.

  1. First, take the left digit and convert it to decimal. Then, multiply the result by 16.
  2. Second, take the right digit and convert it to decimal. Then, sum it with the result of the first step.


- B (hex)
B = 11
Result = 11 (dec)

- A0
A = 10
0 = 0
A * 16  = 160
160 + 0 = 160
Result = 160 (dec)

- FE
F = 15
E = 14
15 * 16 = 240
240 + 14 = 254
Result = 254 (dec)

Easy, isn’t it? A color like khaki (RGB: 240, 230, 140) in hexadecimal equals FF F0 E6 8C. To represent it in HTML you can say #F0E68C.

You can use Windows Calculator (in scientific mode) to make such conversions.