C#中BitConverter.ToUInt16()和BitConverter.ToString()怎么用

发布时间:2021-09-23 11:42:29 作者:小新
来源:亿速云 阅读:151

这篇文章主要为大家展示了“C#中BitConverter.ToUInt16()和BitConverter.ToString()怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“C#中BitConverter.ToUInt16()和BitConverter.ToString()怎么用”这篇文章吧。

第一:排列格式。如:定义一个常量变量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();    }  }}

以上是“C#中BitConverter.ToUInt16()和BitConverter.ToString()怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. C++begin和end运算符的返回迭代器的类型如何判断?
  2. 怎么在C++中使用箭头运算符

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

bitconverter.touint16() bitconverter.tostring()

上一篇:C++中如何使用const、volatile、mutable关键字

下一篇:Java如何使用itext5实现PDF表格文档导出

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》