当前位置: 首页>>代码示例>>C#>>正文


C# Convert.ToByte方法代码示例

本文整理汇总了C#中System.Convert.ToByte方法的典型用法代码示例。如果您正苦于以下问题:C# Convert.ToByte方法的具体用法?C# Convert.ToByte怎么用?C# Convert.ToByte使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Convert的用法示例。


在下文中一共展示了Convert.ToByte方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

//引入命名空间
using System;

public class Example
{
   public static void Main()
   {
      String[] values = { null, "", "0xC9", "C9", "101", "16.3", 
                          "$12", "$12.01", "-4", "1,032", "255",
                          "   16  " };
      foreach (var value in values) {
         try {
            byte number = Convert.ToByte(value);
            Console.WriteLine("'{0}' --> {1}", 
                              value == null ? "<null>" : value, number);
         }
         catch (FormatException) {
            Console.WriteLine("Bad Format: '{0}'", 
                              value == null ? "<null>" : value);
         }
         catch (OverflowException) {
            Console.WriteLine("OverflowException: '{0}'", value);
         }
      }
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:26,代码来源:Convert.ToByte

输出:

'' --> 0
Bad Format: ''
Bad Format: '0xC9'
Bad Format: 'C9'
'101' --> 101
Bad Format: '16.3'
Bad Format: '$12'
Bad Format: '$12.01'
OverflowException: '-4'
Bad Format: '1,032'
'255' --> 255
'   16  ' --> 16

示例2: foreach

ushort[] numbers = { UInt16.MinValue, 121, 340, UInt16.MaxValue };
byte result;
foreach (ushort 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);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:Convert.ToByte

输出:

Converted the UInt16 value 0 to the Byte value 0.
Converted the UInt16 value 121 to the Byte value 121.
The UInt16 value 340 is outside the range of the Byte type.
The UInt16 value 65535 is outside the range of the Byte type.

示例3: foreach

uint[] numbers = { UInt32.MinValue, 121, 340, UInt32.MaxValue };
byte result;
foreach (uint 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);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:Convert.ToByte

输出:

Converted the UInt32 value 0 to the Byte value 0.
Converted the UInt32 value 121 to the Byte value 121.
The UInt32 value 340 is outside the range of the Byte type.
The UInt32 value 4294967295 is outside the range of the Byte type.

示例4: Main

//引入命名空间
using System;

public class Example
{
   public static void Main()
   {
      int[] bases = { 2, 8, 10, 16 };
      string[] values = { "-1", "1", "08", "0F", "11" , "12", "30",                
                          "101", "255", "FF", "10000000", "80" };
      byte number;
      foreach (int numBase in bases)
      {
         Console.WriteLine("Base {0}:", numBase);
         foreach (string value in values)
         {
            try {
               number = Convert.ToByte(value, numBase);
               Console.WriteLine("   Converted '{0}' to {1}.", value, number);
            }   
            catch (FormatException) {
               Console.WriteLine("   '{0}' is not in the correct format for a base {1} byte value.", 
                                 value, numBase);
            }                     
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is outside the range of the Byte type.", value);
            }   
            catch (ArgumentException) {
               Console.WriteLine("   '{0}' is invalid in base {1}.", value, numBase);
            }
         }                                 
      } 
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:34,代码来源:Convert.ToByte

输出:

Base 2:
'-1' is invalid in base 2.
Converted '1' to 1.
'08' is not in the correct format for a base 2 conversion.
'0F' is not in the correct format for a base 2 conversion.
Converted '11' to 3.
'12' is not in the correct format for a base 2 conversion.
'30' is not in the correct format for a base 2 conversion.
Converted '101' to 5.
'255' is not in the correct format for a base 2 conversion.
'FF' is not in the correct format for a base 2 conversion.
Converted '10000000' to 128.
'80' is not in the correct format for a base 2 conversion.
Base 8:
'-1' is invalid in base 8.
Converted '1' to 1.
'08' is not in the correct format for a base 8 conversion.
'0F' is not in the correct format for a base 8 conversion.
Converted '11' to 9.
Converted '12' to 10.
Converted '30' to 24.
Converted '101' to 65.
Converted '255' to 173.
'FF' is not in the correct format for a base 8 conversion.
'10000000' is outside the range of the Byte type.
'80' is not in the correct format for a base 8 conversion.
Base 10:
'-1' is outside the range of the Byte type.
Converted '1' to 1.
Converted '08' to 8.
'0F' is not in the correct format for a base 10 conversion.
Converted '11' to 11.
Converted '12' to 12.
Converted '30' to 30.
Converted '101' to 101.
Converted '255' to 255.
'FF' is not in the correct format for a base 10 conversion.
'10000000' is outside the range of the Byte type.
Converted '80' to 80.
Base 16:
'-1' is invalid in base 16.
Converted '1' to 1.
Converted '08' to 8.
Converted '0F' to 15.
Converted '11' to 17.
Converted '12' to 18.
Converted '30' to 48.
'101' is outside the range of the Byte type.
'255' is outside the range of the Byte type.
Converted 'FF' to 255.
'10000000' is outside the range of the Byte type.
Converted '80' to 128.

示例5:

// Create a hexadecimal value out of range of the Byte type.
string value = SByte.MinValue.ToString("X");
// Convert it back to a number.
try
{
   byte number = Convert.ToByte(value, 16);
   Console.WriteLine("0x{0} converts to {1}.", value, number);
}   
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to a byte.", value);
}
开发者ID:.NET开发者,项目名称:System,代码行数:12,代码来源:Convert.ToByte

示例6: if

// Create a negative hexadecimal value out of range of the Byte type.
sbyte sourceNumber = SByte.MinValue;
bool isSigned = Math.Sign((sbyte)sourceNumber.GetType().GetField("MinValue").GetValue(null)) == -1;
string value = sourceNumber.ToString("X");
byte targetNumber;
try
{
   targetNumber = Convert.ToByte(value, 16);
   if (isSigned && ((targetNumber & 0x80) != 0))
      throw new OverflowException();
   else 
      Console.WriteLine("0x{0} converts to {1}.", value, targetNumber);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert '0x{0}' to an unsigned byte.", value);
} 
// Displays the following to the console:
//    Unable to convert '0x80' to an unsigned byte.
开发者ID:.NET开发者,项目名称:System,代码行数:19,代码来源:Convert.ToByte

示例7: if

//引入命名空间
using System;
using System.Globalization;

public enum SignBit { Negative=-1, Zero=0, Positive=1 };

public struct ByteString : IConvertible
{
   private SignBit signBit;
   private string byteString;
   
   public SignBit Sign
   { 
      set { signBit = value; }
      get { return signBit; }
   }

   public string Value
   { 
      set {
         if (value.Trim().Length > 2)
            throw new ArgumentException("The string representation of a byte cannot have more than two characters.");
         else
            byteString = value;
      }
      get { return byteString; }
   }
   
   // IConvertible implementations.
   public TypeCode GetTypeCode() {
      return TypeCode.Object;
   }
   
   public bool ToBoolean(IFormatProvider provider)
   {
      if (signBit == SignBit.Zero)
         return false;
      else
         return true;
   } 
   
   public byte ToByte(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.", Convert.ToSByte(byteString, 16)));
      else
         return Byte.Parse(byteString, NumberStyles.HexNumber);
   }
   
   public char ToChar(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative) { 
         throw new OverflowException(String.Format("{0} is out of range of the Char type.", Convert.ToSByte(byteString, 16)));
      }
      else {
         byte byteValue = Byte.Parse(this.byteString, NumberStyles.HexNumber);
         return Convert.ToChar(byteValue);
      }                
   } 
   
   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("ByteString to DateTime conversion is not supported.");
   }
   
   public decimal ToDecimal(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative) 
      {
         sbyte byteValue = SByte.Parse(byteString, NumberStyles.HexNumber);
         return Convert.ToDecimal(byteValue);
      }
      else 
      {
         byte byteValue = Byte.Parse(byteString, NumberStyles.HexNumber);
         return Convert.ToDecimal(byteValue);
      }
   }
   
   public double ToDouble(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToDouble(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToDouble(Byte.Parse(byteString, NumberStyles.HexNumber));
   }   
   
   public short ToInt16(IFormatProvider provider) 
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt16(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt16(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
   
   public int ToInt32(IFormatProvider provider) 
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt32(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt32(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
   
   public long ToInt64(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToInt64(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToInt64(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
   
   public sbyte ToSByte(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         try {
            return Convert.ToSByte(Byte.Parse(byteString, NumberStyles.HexNumber));
         }
         catch (OverflowException e) {
            throw new OverflowException(String.Format("{0} is outside the range of the SByte type.", 
                                                   Byte.Parse(byteString, NumberStyles.HexNumber)), e);
         }
      else   
         return SByte.Parse(byteString, NumberStyles.HexNumber);
   }

   public float ToSingle(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         return Convert.ToSingle(SByte.Parse(byteString, NumberStyles.HexNumber));
      else
         return Convert.ToSingle(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public string ToString(IFormatProvider provider)
   {
      return "0x" + this.byteString;
   }
   
   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean: 
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(ByteString).Equals(conversionType))
               return this;
            else
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.", conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(null);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);   
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));   
      }
   }
   
   public UInt16 ToUInt16(IFormatProvider provider) 
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt16 type.", 
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt16(Byte.Parse(byteString, NumberStyles.HexNumber));
   }

   public UInt32 ToUInt32(IFormatProvider provider)
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt32 type.", 
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt32(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
   
   public UInt64 ToUInt64(IFormatProvider provider) 
   {
      if (signBit == SignBit.Negative)
         throw new OverflowException(String.Format("{0} is outside the range of the UInt64 type.", 
                                                   SByte.Parse(byteString, NumberStyles.HexNumber)));
      else
         return Convert.ToUInt64(Byte.Parse(byteString, NumberStyles.HexNumber));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:209,代码来源:Convert.ToByte

示例8: Main

public class Class1
{
   public static void Main()
   {
      byte positiveByte = 216;
      sbyte negativeByte = -101;

      ByteString positiveString = new ByteString();
      positiveString.Sign = (SignBit) Math.Sign(positiveByte);
      positiveString.Value = positiveByte.ToString("X2");
      
      ByteString negativeString = new ByteString();
      negativeString.Sign = (SignBit) Math.Sign(negativeByte);
      negativeString.Value = negativeByte.ToString("X2");
      
      try {
         Console.WriteLine("'{0}' converts to {1}.", positiveString.Value, Convert.ToByte(positiveString));
      }
      catch (OverflowException) {
         Console.WriteLine("0x{0} is outside the range of the Byte type.", positiveString.Value);
      }

      try {
         Console.WriteLine("'{0}' converts to {1}.", negativeString.Value, Convert.ToByte(negativeString));
      }
      catch (OverflowException) {
         Console.WriteLine("0x{0} is outside the range of the Byte type.", negativeString.Value);
      }   
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:30,代码来源:Convert.ToByte

输出:

'D8' converts to 216.
0x9B is outside the range of the Byte type.

示例9: Main

//引入命名空间
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Create a NumberFormatInfo object and set several of its
      // properties that apply to unsigned bytes.
      NumberFormatInfo provider = new NumberFormatInfo();

      // These properties affect the conversion.
      provider.PositiveSign = "pos ";
      provider.NegativeSign = "neg ";

      // This property does not affect the conversion.
      // The input string cannot have a decimal separator.
      provider.NumberDecimalSeparator = ".";
      
      // Define an array of numeric strings.
      string[] numericStrings = { "234", "+234", "pos 234", "234.", "255", 
                                  "256", "-1" };

      foreach (string numericString in numericStrings)
      {
         Console.Write("'{0,-8}' ->   ", numericString);
         try {
            byte number = Convert.ToByte(numericString, provider);
            Console.WriteLine(number);
         }   
         catch (FormatException) {
            Console.WriteLine("Incorrect Format");
         }                             
         catch (OverflowException) {
            Console.WriteLine("Overflows a Byte");
         }   
      }
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:40,代码来源:Convert.ToByte

输出:

'234     ' ->   234
'+234    ' ->   Incorrect Format
'pos 234 ' ->   234
'234.    ' ->   Incorrect Format
'255     ' ->   255
'256     ' ->   Overflows a Byte
'-1      ' ->   Incorrect Format

示例10: ConvertByteSingle

public void ConvertByteSingle(byte byteVal) {
    float floatVal;

    // Byte to float conversion will not overflow.
    floatVal = System.Convert.ToSingle(byteVal);
    System.Console.WriteLine("The byte as a float is {0}.",
        floatVal);

    // Float to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(floatVal);
        System.Console.WriteLine("The float as a byte is {0}.",
            byteVal);
    }
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "The float value is too large for a byte.");
    }
}
开发者ID:.NET开发者,项目名称:System,代码行数:19,代码来源:Convert.ToByte

示例11: foreach

ulong[] numbers= { UInt64.MinValue, 121, 340, UInt64.MaxValue };
byte result;
foreach (ulong 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);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:16,代码来源:Convert.ToByte

输出:

Converted the UInt64 value 0 to the Byte value 0.
Converted the UInt64 value 121 to the Byte value 121.
The UInt64 value 340 is outside the range of the Byte type.
The UInt64 value 18446744073709551615 is outside the range of the Byte type.

示例12: foreach

sbyte[] numbers = { SByte.MinValue, -1, 0, 10, SByte.MaxValue };
byte result;
foreach (sbyte 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);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:16,代码来源:Convert.ToByte

输出:

The SByte value -128 is outside the range of the Byte type.
The SByte value -1 is outside the range of the Byte type.
Converted the SByte value 0 to the Byte value 0.
Converted the SByte value 10 to the Byte value 10.
Converted the SByte value 127 to the Byte value 127.

示例13: ConvertDoubleByte

public void ConvertDoubleByte(double doubleVal) {
    byte	byteVal = 0;

    // Double to byte conversion can overflow.
    try {
        byteVal = System.Convert.ToByte(doubleVal);
        System.Console.WriteLine("{0} as a byte is: {1}.",
            doubleVal, byteVal);
    } 
    catch (System.OverflowException) {
        System.Console.WriteLine(
            "Overflow in double-to-byte conversion.");
    }

    // Byte to double conversion cannot overflow.
    doubleVal = System.Convert.ToDouble(byteVal);
    System.Console.WriteLine("{0} as a double is: {1}.",
        byteVal, doubleVal);
}
开发者ID:.NET开发者,项目名称:System,代码行数:19,代码来源:Convert.ToByte

示例14: foreach

long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
byte result;
foreach (long 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);
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:Convert.ToByte

输出:

The Int64 value -9223372036854775808 is outside the range of the Byte type.
The Int64 value -1 is outside the range of the Byte type.
Converted the Int64 value 0 to the Byte value 0.
Converted the Int64 value 121 to the Byte value 121.
The Int64 value 340 is outside the range of the Byte type.
The Int64 value 9223372036854775807 is outside the range of the Byte type.

示例15: foreach

char[] chars = { 'a', 'z', '\x0007', '\x03FF' };
foreach (char ch in chars)
{
   try {
      byte result = Convert.ToByte(ch);
      Console.WriteLine("{0} is converted to {1}.", ch, result);
   }   
   catch (OverflowException) {
      Console.WriteLine("Unable to convert u+{0} to a byte.", 
                        Convert.ToInt16(ch).ToString("X4"));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:12,代码来源:Convert.ToByte

输出:

a is converted to 97.
z is converted to 122.
is converted to 7.
Unable to convert u+03FF to a byte.


注:本文中的System.Convert.ToByte方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。