Reputation: 405
I would like to convert for example the string "98" to the integer 98. Also, is there a way to specify that the value contained in the string is in hexadecimal and that "98" gets converted to 152?
Upvotes: 3
Views: 295
Reputation: 79
To convert string "98" to the integer 98, use CInt function. For example:
Dim MyString As String = "98"
Dim MyInteger As Integer
MyInteger = CInt(MyString)
Now MyInteger = 98
Upvotes: 1
Reputation: 48949
To convert using decimal notation (base-10):
Dim value = Convert.ToInt32("98")
or
Dim value = Integer.Parse("98")
or
Dim value As Integer
If Integer.TryParse("98", value) Then
Console.WriteLine(value)
End If
To convert using hexadecimal notation (base-16):
Dim value = Convert.ToInt32("98", 16)
or
Dim value = Integer.Parse("98", NumberStyles.HexNumber)
or
Dim value As Integer
If Integer.TryParse("98", NumberStyles.HexNumber, Nothing, value) Then
Console.WriteLine(value)
End If
The NumberStyles
enumeration is in the System.Globalization
namespace.
Upvotes: 0
Reputation: 17845
You would convert the value to Integer with the Parse
method:
Dim intValue As Integer = Integer.Parse("98")
To convert an hexadecimal value you can use the AllowHexSpecifier
option:
Dim intValueFromHex As Integer = Integer.Parse("98", Globalization.NumberStyles.AllowHexSpecifier)
You can also use the TryParse
method if the input value can be in the wrong format:
Dim intValue as integer
If Integer.TryParse("98", intValue)
Console.WriteLine(intValue)
Else
Console.WriteLine("Not an integer value")
End If
Upvotes: 1
Reputation: 5439
I've always been a fan of Integer.TryParse
The docs for .NET 4 are here. This method accepts an Integer variable by reference, and returns a Boolean indicating whether the conversion was successful, so you don't have to do any error handling when calling TryParse
.
If you use the overload that accepts NumberStyle, you can specify that the string contains a hexadecimal number. Here is the overload.
Upvotes: 3