我是靠谱客的博主 迅速芹菜,这篇文章主要介绍C#中BitConverter.ToUInt16()和BitConverter.ToString()的简单使用,现在分享给大家,希望可以做个参考。

下面是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()的用法,这个就是把字节或字节数组转换为十六进制或十六进制的字符串形式,中间用“-”连接


 

 

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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()的简单使用的全部内容,更多相关C#中BitConverter.ToUInt16()和BitConverter.ToString()内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(156)

评论列表共有 0 条评论

立即
投稿
返回
顶部