下面是msdn中的一个例子,在我刚看到这里例子时,该例子有三点是我可以学到的。

第一:排列格式。如:定义一个常量变量const  string  a="{0,11}{1,10},{2,7}"; 这样一个格式用来排列三个变量的位置,第一个变量占5个位置,第二个变量占8个位置,第三个变量占10个位置。中英文都算一个位置。比如在控制台上输出 Console.WriteLine(a,"以后想找什么当另外一半","找个又帅又有车的","那买副象棋吧"); 下面是这个测试的截图


 如果,定义所占的位置少于要输入的字符,会自动增加,而不是截断。

第二:BitConverter.ToUInt16()的用法,是把两个字节转换为无符号整数,如:205 56  这两个字节的16进制是 CD 38  那么转为无符号整数 应该倒过来排 即 38CD  这个数转为无符号十进制整数就是 14541

第三:BitConverter.ToString()的用法,这个就是把字节或字节数组转换为十六进制或十六进制的字符串形式,中间用“-”连接


 

 

下面是这个例子的完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BitConverter数据转换
{
  class Program
  {
    //排列格式,第一个变量占五个位置,第二个变量占17个位置,第三个变量占10个位置
    const string formatter = "{0,5}{1,17}{2,10}";
 
    // Convert two byte array elements to a ushort and display it.
    public static void BAToUInt16(byte[] bytes, int index)
    {
      //BitConverter用于基础数据跟字节数组相互转换
      //BitConverter.ToUInt16()方法将字节数组指定位置起的两个字节转换为无符号整数
      ushort value = BitConverter.ToUInt16(bytes, index);
      //BitConverter.ToString()字节数组转换为十六进制的字符串形式
      Console.WriteLine(formatter, index,
        BitConverter.ToString(bytes, index, 2), value);
    }
    static void Main(string[] args)
    {
      byte[] byteArray = {
      15, 0, 0, 255, 3, 16, 39, 255, 255, 127 };
      Console.WriteLine(
        "This example of the BitConverter.ToUInt16( byte[ ], " +
        "int ) \nmethod generates the following output. It " +
        "converts elements \nof a byte array to ushort values.\n");
      Console.WriteLine("initial byte array");
      Console.WriteLine("------------------");
      Console.WriteLine(BitConverter.ToString(byteArray));
      Console.WriteLine();
      Console.WriteLine(formatter, "index", "array elements",
        "ushort");
      Console.WriteLine(formatter, "-----", "--------------",
        "------");
      // Convert byte array elements to ushort values.
      BAToUInt16(byteArray, 1);
      BAToUInt16(byteArray, 0);
      BAToUInt16(byteArray, 3);
      BAToUInt16(byteArray, 5);
      BAToUInt16(byteArray, 8);
      BAToUInt16(byteArray, 7);
      Console.ReadKey();
    }
  }
}

以上就是【.NET C#中BitConverter.ToUInt16()和BitConverter.ToString()的简单使用】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论