Convert to byte
In this chapter you will learn:
Convert int to byte
using System;/*ja va 2 s.c o m*/
public class Example
{
public static void Main()
{
int int1 = 128;
try {
byte value1 = (byte) int1;
Console.WriteLine(value1);
}
catch (OverflowException) {
Console.WriteLine("{0} is out of range of a byte.", int1);
}
}
}
Convert double to byte
using System;// ja v a 2 s . c o m
public class Example
{
public static void Main()
{
double dbl2 = 3.99;
try {
byte value2 = (byte) dbl2;
Console.WriteLine(value2);
}
catch (OverflowException) {
Console.WriteLine("{0} is out of range of a byte.", dbl2);
}
}
}
Using Convert.ToByte to convert value to byte
using System;// j a va 2s . c om
public class Example
{
public static void Main()
{
int[] numbers = { Int32.MinValue, -1, 0, 121, 128,340, Int32.MaxValue };
byte result;
foreach (int number in numbers)
{
try {
result = Convert.ToByte(number);
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
number.GetType().Name, number,
result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
number.GetType().Name, number);
}
}
}
}
Next chapter...
What you will learn in the next chapter:
- 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
Home » C# Tutorial » Byte, Integer, Long