开发者

Convert music file to byte array c# like matlab

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.


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


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜