从字节数组中读取单字节的最佳方法

Ank*_*dra -2 c# arrays byte

我有字节数组,我想逐个读取这些字节并将其转换为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
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,但性能观点是那么好或有更好的方法来处理这个?

Nic*_*rey 6

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 ) ;
Run Code Online (Sandbox Code Playgroud)

产生预期的:

The date is: Friday, October 25, 2013 4:16:26 AM
Run Code Online (Sandbox Code Playgroud)

  • @GrantWinney.固定它.我告诉你,这是药物! (3认同)