C# Convert ToInt16(String, Int32)

Description

Convert ToInt16(String, Int32) converts the string representation of a number in a specified base to an equivalent 16-bit signed integer.

Syntax

Convert.ToInt16(String, Int32) has the following syntax.


public static short ToInt16(
  string value,
  int fromBase
)

Parameters

Convert.ToInt16(String, Int32) has the following parameters.

  • value - A string that contains the number to convert.
  • fromBase - The base of the number in value, which must be 2, 8, 10, or 16.

Returns

Convert.ToInt16(String, Int32) method returns A 16-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null.

Example

The following example attempts to interpret each element in a string array as a hexadecimal string and to convert it to a 16-bit signed integer.


//  w  ww .  j  a v a2 s . c  om
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 {
            short number = Convert.ToInt16(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 code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version