Convert to byte

In this chapter you will learn:

  1. Convert int to byte
  2. Convert double to byte
  3. Using Convert.ToByte to convert value to byte

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:

  1. Parse string to byte and catch the OverflowException and FormatException
  2. Parse hexadecimal number to byte
  3. Parse string with a culture-specific format to byte
  4. Tries to parse string to Byte
  5. Parse byte value with trailing sign or leading sign
Home » C# Tutorial » Byte, Integer, Long
Integer Family
Integer ranges
byte
Convert to byte
Parse string to byte
byte format
byte octal and hexadecimal
byte binary operation
byte overflow with unchecked
int
int value
Compare int value
int calculation
int value overflow
int binary operation
Parse string to int value
Format int value
int in binary, octal and hexadecimal
long
long value calculation
ulong