2015-11-05 37 views
0

我看第x字節從特定的文件:比較中有單位值從文件中讀取的字節

 uint LIBPCAP_MAGIC = 0xa1b2c3d4; 
     uint LIBPCAP_MAGIC_ENDIAN = 0xd4c3b2a1; 

     using (BinaryReader binaryReader = new BinaryReader(File.Open("file", FileMode.Open))) 
     { 
      byte[] buffer = binaryReader.ReadBytes(50); 

      for (int i = 0; i < buffer.Length - 4; i++) 
      { 
       uint currentValue = BitConverter.ToUInt32(buffer, i); 
       if (currentValue == LIBPCAP_MAGIC || currentValue == LIBPCAP_MAGIC_ENDIAN) 
        Console.WriteLine("FOUND!!!"); 
      } 
     } 

之後,我有這個常數uint值:

uint LIBPCAP_MAGIC_NUMBER = 0xd4c3b2a1; 

,我想作確定如果我的第一個x bytes(在本例中爲20個字節)包含此uint值。

所以在這個例子中,我有這個string hex,但我想知道這是讀取字節並轉換爲string hex的最佳方法。 也許我需要閱讀bytes而不是轉換它?

+0

'BitConverter.ToUInt32'可以做到這一點。您不需要轉換爲字符串十六進制只使用字節。 uint只有4個字節,所以不知道如何將其與20個字節進行比較https://msdn.microsoft.com/zh-cn/library/system.bitconverter.touint32(v=vs.110).aspx –

+0

我可以嗎?有代碼示例? –

回答

2

我完全跳過十六進制的轉換,只需使用一個滑動的轉換,這是假設VALUE可以在第20個字節中找到任何地方

public static void Main() 
{ 
    uint VALUE = 0xe3c6a7d1; 
    using (BinaryReader binaryReader = new BinaryReader(File.Open("File.bin", FileMode.Open))) 
    { 
     byte[] buffer = binaryReader.ReadBytes(20); 

     for (int i = 0; i < buffer.Length - 4; i++) 
     { 
      byte[] temp = new byte[4]; 
      Buffer.BlockCopy(buffer, i, temp, 0, 4); 
      temp = temp.Reverse().ToArray(); 
      uint currentValue = BitConverter.ToUInt32(temp, 0); 
      if (currentValue == VALUE) 
       Console.WriteLine("FOUND!!!"); 
     } 
    } 

    Console.ReadLine(); 
} 

正在發生的事情是,你將前20個字節立即讀入緩衝區,然後使用for-loop搜索緩衝區,將當前位置的4個字節(i)轉換爲uint,並將其與VALUE進行比較。

+1

這永遠不會進入if語句 –

+0

您確定前20個字節包含示例文件的'uint'值嗎?示例文件中的字節順序是否顛倒了? –

+0

是的裏面,順便說一句我編輯我搜索的uint值。 –