迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

在 C# 中将 Int 转换为字节

作者:迹忆客 最近更新:2024/01/16 浏览次数:

我们将研究在 C# 中将 Int 转换为 Byte[] 的几种不同技术。


C# 中使用 ToByte(String) 方法将 Int 转换为 Byte[]

这种方法通过使用 ToByte(String) 方法将提供的数字字符串表示形式转换为等效的 8 位无符号整数来工作。它作为一个字符串参数,包含要转换的数字。

下面的示例创建一个字符串数组并将每个字符串转换为一个字节。

首先,添加这些库。

using System;
using System.Diagnostics;

我们首先创建一个名为 Alldatavaluesstring[] 类型变量并分配一些值。

string[] Alldatavalues = { null, "", "3227", "It5", "99", "9*9", "25.6", "$50", "-11", "St8" };

现在使用 Convert.ToByte() 使用 for each 循环将整数转换为字节。

byte num = Convert.ToByte(value);

当值没有可选符号后跟一系列数字时,会发生格式异常(0 到 9)。我们利用 FormatException 处理程序来克服这个问题。

catch (FormatException) {
  Console.WriteLine("Unsuported Format: '{0}'", value == null ? "<null>" : value);
}

当值反映小于 MinValue 或大于 MaxValue 时,会出现溢出错误。

catch (OverflowException) {
  Console.WriteLine("Data Overflow Exception: '{0}'", value);
}

源代码:

using System;
using System.Diagnostics;

public class ToByteString {
  public static void Main() {
    string[] Alldatavalues = { null, "", "3227", "It5", "99", "9*9", "25.6", "$50", "-11", "St8" };
    foreach (var value in Alldatavalues) {
      try {
        byte num = Convert.ToByte(value);
        Console.WriteLine("'{0}' --> {1}", value == null ? "<null>" : value, num);
      } catch (FormatException) {
        Console.WriteLine("Unsupported Format: '{0}'", value == null ? "<null>" : value);
      } catch (OverflowException) {
        Console.WriteLine("Data Overflow Exception: '{0}'", value);
      }
    }
  }
}

输出:

'<null>' --> 0
Unsupported Format: ''
Data Overflow Exception: '3227'
Unsupported Format: 'It5'
'99' --> 99
Unsupported Format: '9*9'
Unsupported Format: '25.6'
Unsupported Format: '$50'
Data Overflow Exception: '-11'
Unsupported Format: 'St8'

C# 中使用 ToByte(UInt16) 方法将 Int 转换为 Byte[]

ToByte(UInt16) 方法将 16 位无符号整数的值转换为等效的 8 位无符号整数。要进行转换,它需要一个 16 位无符号整数作为参数。

在以下示例中,无符号 16 位整数数组被转换为字节值。

要添加的库有:

using System;
using System.Diagnostics;

首先,初始化一个名为 dataushort[] 类型变量;之后,我们将为其分配一些值,例如 UInt16.MinValue 作为最小值,UInt16.MaxValue 作为最大值以及我们想要转换的其他值,就像我们插入 90880 .

ushort[] data = { UInt16.MinValue, 90, 880, UInt16.MaxValue };

然后我们将创建一个名为 resultbyte 类型变量。

byte result;

之后,应用一个 for each 循环,它将转换为 Byte 类型的数据;除此之外,如果一个数字超出 Byte 的范围,它将显示异常。

foreach (ushort numberdata in data) {
  try {
    result = Convert.ToByte(numberdata);
    Console.WriteLine("Successfully converted the {0} value {1} to the {2} value {3}.",
                      numberdata.GetType().Name, numberdata, result.GetType().Name, result);
  } catch (OverflowException) {
    Console.WriteLine("The {0} value {1} is outside the range of Byte.", numberdata.GetType().Name,
                      numberdata);
  }
}

源代码:

using System;
using System.Diagnostics;

public class ToByteString {
  public static void Main() {
    ushort[] data = { UInt16.MinValue, 90, 880, UInt16.MaxValue };
    byte result;

    foreach (ushort numberdata in data) {
      try {
        result = Convert.ToByte(numberdata);
        Console.WriteLine("Successfully converted the {0} value {1} to the {2} value {3}.",
                          numberdata.GetType().Name, numberdata, result.GetType().Name, result);
      } catch (OverflowException) {
        Console.WriteLine("The {0} value {1} is outside the range of Byte.",
                          numberdata.GetType().Name, numberdata);
      }
    }
  }
}

输出:

Successfully converted the UInt16 value 0 to the Byte value 0.
Successfully converted the UInt16 value 90 to the Byte value 90.
The UInt16 value 880 is outside the range of Byte.
The UInt16 value 65535 is outside the range of Byte.

C# 中使用 ToByte(String, Int32) 方法将 Int 转换为 Byte[]

此方法将数字的字符串表示形式转换为给定基数的等效 8 位无符号整数。它需要一个包含要转换的数字的 string 参数值。

将添加以下库。

using System;
using System.Diagnostics;

首先,我们将构造一个名为 Allbasedataint[] 类型变量并分配基数 810

int[] Allbasedata = { 8, 10 };

现在我们创建一个名为 valuesstring[] 类型变量并为其赋值,并声明一个名为 numberbyte 类型变量。

string[] values = { "80000000", "1201", "-6", "6", "07", "MZ", "99", "12", "70", "255" };
byte number;

然后我们将应用一个 foreach 循环,它将数字转换为 byte 格式,它还将处理以下异常:

  1. FormatException:当值包含的字符不是来自 base 提供的 base 中的有效数字时,会发生此错误。
  2. OverflowException:当负号前缀到表示以 10 为基数的无符号数的值时,会发生此错误。
  3. ArgumentException:当值为空时发生此错误。
foreach (string value in values) {
  try {
    number = Convert.ToByte(value, numberBase);
    Console.WriteLine("   Converted '{0}' to {1}.", value, number);
  } catch (FormatException) {
    Console.WriteLine("   '{0}' is an Invalid format for a base {1} byte value.", value,
                      numberBase);
  } catch (OverflowException) {
    Console.WriteLine("   '{0}' is Outside the Range of Byte type.", value);
  } catch (ArgumentException) {
    Console.WriteLine("   '{0}' is invalid in base {1}.", value, numberBase);
  }
}

源代码:

using System;
using System.Diagnostics;

public class ToByteStringInt32 {
  public static void Main() {
    int[] Allbasedata = { 8, 10 };
    string[] values = { "80000000", "1201", "-6", "6", "07", "MZ", "99", "12", "70", "255" };
    byte number;
    foreach (int numberBase in Allbasedata) {
      Console.WriteLine("Base Number {0}:", numberBase);
      foreach (string value in values) {
        try {
          number = Convert.ToByte(value, numberBase);
          Console.WriteLine("   Converted '{0}' to {1}.", value, number);
        } catch (FormatException) {
          Console.WriteLine("   '{0}' is an Invalid format for a base {1} byte value.", value,
                            numberBase);
        } catch (OverflowException) {
          Console.WriteLine("   '{0}' is Outside the Range of Byte type.", value);
        } catch (ArgumentException) {
          Console.WriteLine("   '{0}' is invalid in base {1}.", value, numberBase);
        }
      }
    }
  }
}

输出:

Base Number 8:
   '80000000' is an Invalid format for a base 8 byte value.
   '1201' is Outside the Range of Byte type.
   '-6' is invalid in base 8.
   Converted '6' to 6.
   Converted '07' to 7.
   'MZ' is an Invalid format for a base 8 byte value.
   '99' is an Invalid format for a base 8 byte value.
   Converted '12' to 10.
   Converted '70' to 56.
   Converted '255' to 173.
Base Number 10:
   '80000000' is Outside the Range of Byte type.
   '1201' is Outside the Range of Byte type.
   '-6' is Outside the Range of Byte type.
   Converted '6' to 6.
   Converted '07' to 7.
   'MZ' is an Invalid format for a base 10 byte value.
   Converted '99' to 99.
   Converted '12' to 12.
   Converted '70' to 70.
   Converted '255' to 255.

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 C# 中发出 HTTP POST Web 请求

发布时间:2024/02/04 浏览次数:131 分类:编程语言

在 C# 中,可以使用 3 种主要方法来发出 HTTP POST Web 请求:WebClient 类,HttpWebRequest 类和 HttpClient 类。本教程将讨论在 C# 中发出 HTTP POST Web 请求的方法。使用 C# 中的 WebClient 类发出 HTTP POST Web 请求

在 C# 中调整图像大小

发布时间:2024/02/04 浏览次数:203 分类:编程语言

有两种主要方法可用于在 C# 中调整图像的大小,Bitmap 类构造函数和 graphics.DrawImage()函数。在本教程中,我们将讨论在C#中调整图像大小的方法。我们将带您完成整个过程,从加载原始图像到保

在 C# 中下载图片

发布时间:2024/02/04 浏览次数:138 分类:编程语言

有 3 种主要方法可用于下载 C# 中的图片,WebClient.DownloadFile()函数,Bitmap 类和 Image.FromStream()函数。在 C# 中使用 WebClient 类下载图片 WebClient 类提供了用于向 C# 中的 URL 发送数据和从 URL 接收数据

在 C# 中使用秒表

发布时间:2024/02/04 浏览次数:139 分类:编程语言

我们可以使用 Stopwatch 类来计算 C# 中的经过时间。使用 C# 中的秒表类计算经过时间 Stopwatch 类在 C# 中准确测量经过的时间。

在 C# 中获取可执行路径

发布时间:2024/02/04 浏览次数:200 分类:编程语言

有 3 种主要方法可用于获取 C# 中程序的可执行路径,即 Assembly 类,AppDomain 类和 Path 类。本教程将介绍获取 C# 代码的可执行路径的方法。使用 C# 中的 Assembly 类获取可执行路径

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便