Ram Prasad

Ram Prasad

  • NA
  • 326
  • 16.8k

dividing binary data into smaller chunks

Jul 21 2020 5:10 PM
I am trying to divide binary data into small chunks from .txt file using the code below. However, this code is reading 0 and 1 in ASCII code and showing the results in 48 and 49 respectively. How can I fix this?
 
For Ex: 0101 is being read as 48494849.
  1. public static IEnumerable<IEnumerable<byte>> ReadByChunk(int chunkSize)  
  2. {  
  3. IEnumerable<byte> result;  
  4. int startingByte = 0;  
  5. do  
  6. {  
  7. result = ReadBytes(startingByte, chunkSize);  
  8. startingByte += chunkSize;  
  9. yield return result;  
  10. while (result.Any());  
  11. }  
  12. public static IEnumerable<byte> ReadBytes(int startingByte, int byteToRead)  
  13. {  
  14. byte[] result;  
  15. using (FileStream stream = File.Open(@"C:\Users\file.txt", FileMode.Open, FileAccess.Read, FileShare.Read))  
  16. using (BinaryReader reader = new BinaryReader(stream))  
  17. {  
  18. int bytesToRead = Math.Max(Math.Min(byteToRead, (int)reader.BaseStream.Length - startingByte), 0);  
  19. reader.BaseStream.Seek(startingByte, SeekOrigin.Begin);  
  20. result = reader.ReadBytes(bytesToRead);  
  21. }  
  22. return result;  
  23. }  
  24. public static void Main()  
  25. {  
  26. foreach (IEnumerable<byte> bytes in ReadByChunk(chunkSize))  
  27. {  
  28. // more code  
  29. }  
  30. }  

Answers (4)