1

I would like to convert any music file into a byte array and print the result in c# just like in MATLAB.

I tried this;

System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
_Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);

And the code to print to console:

Console.WriteLine( byteArrayToString(fileToByteArray("Penguins.jpg")) );

where the method's code is:

private static string byteArrayToString(byte[] p)
{
    string result = System.Text.ASCIIEncoding.ASCII.GetString(p);
    return result;
}

When I run this code, console becomes crazy with irrelevant characters, however I would like to have an array like MATLAB's output.

How should I do that ?

Thanks.

8
  • FYI, this code can be simplified to File.ReadAllBytes(_FileName)... Commented Aug 2, 2011 at 9:12
  • And where's the code that prints to the console? You're only showing how you load the data from the file Commented Aug 2, 2011 at 9:13
  • Code is: Console.WriteLine(byteArrayToString(fileToByteArray("C:\\Users\\Public\\Pictures\\Sample Pictures/Penguins.jpg"))); and the method's code is: private static string byteArrayToString(byte[] p) { string result = System.Text.ASCIIEncoding.ASCII.GetString(p); return result; } Commented Aug 2, 2011 at 9:21
  • don't post it in a comment, its really hard to read... edit your question instead Commented Aug 2, 2011 at 9:28
  • @Can, What does the output in MatLab look like? Commented Aug 2, 2011 at 9:29

2 Answers 2

2

If you just want the byte array of any file just do the following:

byte[] byteArrayFile = File.ReadAllBytes(source);
//source is the path to the file
Sign up to request clarification or add additional context in comments.

Comments

0

Do you really want characters? If you just want the numbers, build a string with the numbers. I don't know matlabs format, but say for a row vector like [N1,N2,N3]

private static string ByteArrayToString(byte[] p)
{
     StringBuilder sb = new StringBuilder("[");
     for(int i=0; i<p.Length; i++)
     {
          sb.Append(p[i]);
          if (i < p.Length - 1)
              sb.Append(',');
     }
     sb.Append("]");
     return sb.ToString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.