【问题标题】:Best way to read single byte from array of bytes从字节数组中读取单个字节的最佳方法
【发布时间】:2015-06-03 00:55:32
【问题描述】:

我有一个字节数组,我想一个一个地读取这些字节并将其转换为 int。我正在获取数组字节中的日期,因此需要从中创建 DataTime 对象。我正在使用以下代码。从性能的角度来看,最好的方法应该是什么。

byte[] date = {25, 10, 13, 04, 16, 26} //day month year hour minute second

CaptureTime = new DateTime(
                        (int)(new ArraySegment<byte>(date, 2, 1).ToArray()[0]), // Year
                        (int)(new ArraySegment<byte>(date, 1, 1).ToArray()[0]), // Month
                        (int)(new ArraySegment<byte>(date, 0, 1).ToArray()[0]), // Day
                        (int)(new ArraySegment<byte>(date, 3, 1).ToArray()[0]), //Hours
                        (int)(new ArraySegment<byte>(date, 4, 1).ToArray()[0]), //Minutes
                        (int)(new ArraySegment<byte>(date, 5, 1).ToArray()[0])); //Seconds

上面的代码运行良好,但从性能角度来看还不错,还是有更好的方法来处理这个问题?

【问题讨论】:

  • 我投票结束这个问题作为离题,因为这更适合 codereview.stackexchange.com
  • wtf 错了(int)date[2]
  • 代码显然缺少与字符串的一对转换:)... 真的不明白你为什么要把这么复杂的代码作为起点。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# arrays byte


【解决方案1】:

byte 是一个 8 位无符号整数,在需要时会隐式向上转换为 int

也许我想的太少了,但是明显而有效的有什么问题:

byte[] octets = {25, 10, 13, 04, 16, 26} //day month year hour minute second

DateTime date = new DateTime(
                  2000 + octets[2] , // year
                         octets[1] , // month
                         octets[0] , // day
                         octets[3] , // hour
                         octets[4] , // minutes
                         octets[5]   // seconds
                ) ;
Console.WriteLine( "The date is: {0:F}" , date ) ;

产生预期的结果:

The date is: Friday, October 25, 2013 4:16:26 AM

【讨论】:

  • @GrantWinney。修复。是毒品,我告诉你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多