Parse string to byte
In this chapter you will learn:
- Parse string to byte and catch the OverflowException and FormatException
- Parse hexadecimal number to byte
- Parse string with a culture-specific format to byte
- Tries to parse string to Byte
- Parse byte value with trailing sign or leading sign
Parse and check the exception
using System;/*from j a v a 2 s. c o m*/
public class Example
{
public static void Main()
{
string string1 = "244";
try {
byte byte1 = Byte.Parse(string1);
Console.WriteLine(byte1);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is out of range of a byte.", string1);
}
catch (FormatException) {
Console.WriteLine("'{0}' is out of range of a byte.", string1);
}
}
}
Parse hexadecimal number to byte
using System;/*from j a v a 2 s.co m*/
public class Example
{
public static void Main()
{
string string2 = "A1";
try {
byte byte2 = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(byte2);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is out of range of a byte.", string2);
}
catch (FormatException) {
Console.WriteLine("'{0}' is out of range of a byte.", string2);
}
}
}
Parse with a culture-specific format
using System;// ja v a 2 s . co m
using System.Globalization;
public class Example
{
public static void Main()
{
byte byteValue;
string stringToConvert = " 214 ";
try {
byteValue = Byte.Parse(stringToConvert, CultureInfo.InvariantCulture);
Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, byteValue);
}
catch (FormatException) {
Console.WriteLine("Unable to parse '{0}'.", stringToConvert);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is greater than {1} or less than {2}.",
stringToConvert, Byte.MaxValue, Byte.MinValue);
}
}
}
Tries to parse
using System;/* j a va 2 s . c o m*/
public class ByteConversion
{
public static void Main()
{
string byteString = "0x1F";
CallTryParse(byteString);
}
private static void CallTryParse(string stringToConvert)
{
byte byteValue;
bool result = Byte.TryParse(stringToConvert, out byteValue);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}", stringToConvert, byteValue);
}
}
}
Parse byte value with trailing sign or leading sign
using System;/*from j a v a 2 s . co m*/
using System.Globalization;
public class Example
{
public static void Main()
{
string value;
NumberStyles style;
byte number;
// Parse value with trailing sign.
style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
value = " 1+";
number = Byte.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
// Parse value with leading sign.
value = " +2 ";
number = Byte.Parse(value, style);
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Byte, Integer, Long