Export (0) Print
Expand All

Convert.ToUInt16 Method (String, Int32)

Converts the string representation of a number in a specified base to an equivalent 16-bit unsigned integer.

This API is not CLS-compliant. 

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[CLSCompliantAttribute(false)]
public static ushort ToUInt16(
	string value,
	int fromBase
)

Parameters

value
Type: System.String

A string that contains the number to convert.

fromBase
Type: System.Int32

The base of the number in value, which must be 2, 8, 10, or 16.

Return Value

Type: System.UInt16
A 16-bit unsigned integer that is equivalent to the number in value, or 0 (zero) if value is null.

ExceptionCondition
ArgumentException

fromBase is not 2, 8, 10, or 16.

-or-

value, which represents a non-base 10 unsigned number, is prefixed with a negative sign.

ArgumentOutOfRangeException

value is String.Empty.

FormatException

value contains a character that is not a valid digit in the base specified by fromBase. The exception message indicates that there are no digits to convert if the first character in value is invalid; otherwise, the message indicates that value contains invalid trailing characters.

OverflowException

value, which represents a non-base 10 unsigned number, is prefixed with a negative sign.

-or-

value represents a number that is less than UInt16.MinValue or greater than UInt16.MaxValue.

If fromBase is 16, you can prefix the number specified by the value parameter with "0x" or "0X".

Because the UInt16 data type supports unsigned values only, the ToUInt16(String, Int32) method assumes that value is expressed using unsigned binary representation. In other words, all 16 bits are used to represent the numeric value, and a sign bit is absent. As a result, it is possible to write code in which a signed integer value that is out of the range of the UInt16 data type is converted to a UInt16 value without the method throwing an exception. The following example converts Int16.MinValue to its hexadecimal string representation, and then calls the ToUInt16(String, Int32) method. Instead of throwing an exception, the method displays the message, "0x8000 converts to 32768."

// Create a hexadecimal value out of range of the UInt16 type. 
string value = Convert.ToString(Int16.MinValue, 16);
// Convert it back to a number. 
try
{
   UInt16 number = Convert.ToUInt16(value, 16);
   Console.WriteLine("0x{0} converts to {1}.", value, number);
}   
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned short integer.", 
                     value);
}   

When performing binary operations or numeric conversions, it is always the responsibility of the developer to verify that a method or operator is using the appropriate numeric representation to interpret a particular value. The following example illustrates one technique for ensuring that the method does not inappropriately use binary representation to interpret a value that uses two's complement representation when converting a hexadecimal string to a UInt16 value. The example determines whether a value represents a signed or an unsigned integer while it is converting that value to its string representation. When the example converts the value to a UInt16 value, it checks whether the original value was a signed integer. If so, and if its high-order bit is set (which indicates that the original value was negative), the method throws an exception.

// Create a negative hexadecimal value out of range of the UInt16 type. 
short sourceNumber = Int16.MinValue;
bool isSigned = Math.Sign((short)sourceNumber.GetType().GetField("MinValue").GetValue(null)) == -1;
string value = Convert.ToString(sourceNumber, 16);
UInt16 targetNumber;
try
{
   targetNumber = Convert.ToUInt16(value, 16);
   if (isSigned && ((targetNumber & 0x8000) != 0))
      throw new OverflowException();
   else 
      Console.WriteLine("0x{0} converts to {1}.", value, targetNumber);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned short integer.", value);
} 
// Displays the following to the console: 
//    Unable to convert '0x8000' to an unsigned short integer.     

The following example attempts to interpret each element in an array of numeric strings as a hexadecimal value and to convert it to an unsigned 16-bit integer.

using System;

public class Example
{
   public static void Main()
   {
      string[] hexStrings = { "8000", "0FFF", "f000", "00A30", "D", "-13", 
                              "9AC61", "GAD" };
      foreach (string hexString in hexStrings)
      {
         try {
            ushort number = Convert.ToUInt16(hexString, 16);
            Console.WriteLine("Converted '{0}' to {1:N0}.", hexString, number);
         }
         catch (FormatException) {
            Console.WriteLine("'{0}' is not in the correct format for a hexadecimal number.", 
                              hexString);
         }
         catch (OverflowException) {
            Console.WriteLine("'{0}' is outside the range of an Int16.", hexString);
         }
         catch (ArgumentException) {
            Console.WriteLine("'{0}' is invalid in base 16.", hexString);
         }
      }                                            
   }
}
// The example displays the following output: 
//    Converted '8000' to 32,768. 
//    Converted '0FFF' to 4,095. 
//    Converted 'f000' to 61,440. 
//    Converted '00A30' to 2,608. 
//    Converted 'D' to 13. 
//    '-13' is invalid in base 16. 
//    '9AC61' is outside the range of an Int16. 
//    'GAD' is not in the correct format for a hexadecimal number.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft