Search This Blog

Thursday, January 8, 2009

VB.NET - Converting Integers to Binary, Octal or Hexadecimal

Convert Integers to Binary, Octal or Hexadecimal

For readability it is usual to present integer values using the decimal numbering system. However, sometimes the binary, hexadecimal or octal number bases are more appropriate. This tip shows how to convert a value to one of these alternatives.

Convert.ToString Method

The .NET framework does not provide a special data type for holding a value in different number bases. For this article, we will simply be using the standard integer data types, which are generally displayed in decimal but which are held in memory using binary.To convert the numbers to a non-decimal system, the ToString method in the Convert class is used and the results are returned as a string.

The conversion described can be performed on any of the signed integer data types (short, int or long) or the byte data type. To convert any of these types, the Convert.ToString method is used with two parameters. The first parameter is the value to be processed. The second parameter holds the number base that is required. The number base may be 2 for binary, 8 for octal, 10 for decimal or 16 for hexadecimal. Using any other value causes an exception.

The following example demonstrates the conversion to all three non-decimal variations using a console application:

Console.WriteLine(Convert.ToString(value, 2));      // Outputs "10101010" Console.WriteLine(Convert.ToString(value, 8));      // Outputs "271" Console.WriteLine(Convert.ToString(value, 16));     // Outputs "b9"

Adding Leading Zeroes

The conversion process produces a string containing the converted value without leading zeroes. To pad the string with zeroes to achieve a specific length, the PadLeft method can be used. The first parameter of the method sets the target length for the converted string and the second parameter is the padding character, in this case a zero.

int value = 31;  string binary = Convert.ToString(value, 2); Console.WriteLine(binary.PadLeft(8, '0'));          // Outputs "00011111"

No comments: