2013-04-17 1 views
0

난 당신이 그림 우는 소리에서 볼 수 있도록이 문제에 대한 몇 가지 도움을받을 기대했다 읽기 : enter image description here는 C# 이진, 내가 0x00으로까지 전체 단어를 읽을 수없는 것 불완전 문자열

무엇 내가 해주 마 노력하고, 여기에, 단지 제대로 파일 문자열을 읽을 수있는 내가 파일을 여는 데 사용되는 코드입니다

 private void menuItem2_Click(object sender, EventArgs e) 
    { 
     listView1.Items.Clear(); 
     textBox1.Text = ""; 
     menuItem12.Text = "file type is: "; 
     OpenFileDialog ofd = new OpenFileDialog(); 
     ofd.Title = "Open File"; 
     ofd.Filter = "All Files (*.*)|*.*"; 
     if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      path = ofd.FileName; 
      BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("SHIFT-JIS")); 
      foreach (char mychar in br.ReadChars(4)) menuItem12.Text += mychar; 
      if (menuItem12.Text != "file type is: TXTD") 
      { 
       MessageBox.Show("This is not a TXTD file...", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error); 
       return; 
      } 
      else 
      { 
        MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        br.BaseStream.Position = 0x8; 
        int Pntrnum = br.ReadInt16(); 
        menuItem11.Visible = true; 
        menuItem11.Text = Pntrnum.ToString(); 
        List<int> offsets = new List<int>(); 
        br.BaseStream.Position = 0x10; 
        for (int i = 0; i < Pntrnum; i++) 
        { 
         offsets.Add(br.ReadInt32()); 
        } 
        Dictionary<int, string> values = new Dictionary<int, string>(); 
        for (int i = 0; i < offsets.Count; i++) 
        { 
         int currentOffset = offsets[i]; 

         int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length; 

         int stringLength = (nextOffset - currentOffset - 1)/2; 

         br.BaseStream.Position = currentOffset; 

         var chars = br.ReadChars(stringLength); 
         values.Add(currentOffset, new String(chars)); 
        } 

        foreach (int offset in offsets) 
        { 
         listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]); 
        } 

        br.Close(); 
        br = null; 
      } 
     } 
     ofd.Dispose(); 
     ofd = null; 
    } 
+1

'stringLength = (nextOffset - currentOffset - 1)/2'에서 왜 2로 나눕니 까? ("SHIFT-JIS"인코딩은 ASCII 범위의 1 바이트 문자를 가지고 있다고 생각합니다.) –

+0

고맙습니다, 선생님, 거기서 보지 못했습니다. 솔루션으로 게시 해주세요. 선택할 수 있습니다 :) 다시 고마워요. – Omarrrio

답변

2

은 "SHIFT-JIS"인코딩이 ASCII 범위의 문자를 단일 바이트를 사용하여 볼 수 있습니다.

나는 당신의 텍스트가 ASCII 것을 볼 수 있지만,이 코드 줄 :

stringLength = (nextOffset - currentOffset - 1)/2; 

는 문자가 2 바이트를 점유하는 것으로 가정한다.

1

적절한 문자열로 이진 데이터를 변환하기 위해서는 당신에 대한 Encodings을 알아야한다. 따라서 유용한 인코딩은 System.Text.Encoding에서 찾을 수 있습니다. 그럼 당신은 다음과 같은 문자열로 바이트 배열을 변환 할 수 있습니다

byte[] byteArray = // your byte array 
System.Text.Encoding encoding = Encoding.UTF8; //use proper encoding 
string value = encoding.GetString(byteArray); 

은 또한 당신은 MSDN