I have a text file filled with hex datas(like "FFD8FE00..") of a .mjpeg formatted file. I have to play it with a converter. So, i am trying to write the data in a .mjpeg file with these lines:
string myData = File.ReadAllText("hexData.txt");
string newData;
int remainder = myData.Length%500;
byte[] data_toWrite=newByte[250];
for(int i=0;i<myData.Length-remainder; i+=500)
{
newData = myData.Substring(i,500);
data_toWrite = StringToByteArray(newData);
File.WriteAllBytes("video.mjpeg",data_toWrite);
}
newData = myData.Substring(myData.Length-remainder,remainder);
data_toWrite = StringToByteArray(newData);
File.WriteAllBytes("video.mjpeg",data_toWrite);
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
But i couldn't make it play. I don't know where I am wrong at. I tried to convert newData to ascii then byte array but it failed,too.
Any ideas,many thanks!
Kane
This
File.WriteAllBytes("video.mjpeg",data_toWrite);
overwrites the file every time, not appends.
I'm sure better code can be written, but this should be enough:
string input = "test.hex";
string output = "output.bin";
using (var sr = new StreamReader(input))
using (var fs = File.Create(output))
{
// We accumulate the 2 hex digits needed for a byte here
string h = string.Empty;
while (true)
{
int ch1 = sr.Read();
if (ch1 == -1)
{
// The file finished but we have a pending partial hex code
if (h.Length == 1)
{
throw new Exception("Malformed file");
}
break;
}
char ch2 = (char)ch1;
// Skip white space and end-of-line
if (char.IsWhiteSpace(ch2))
{
continue;
}
h += ch2;
// We have collected 2 hex digits, so we have 1 byte
if (h.Length == 2)
{
byte b = Convert.ToByte(h, 16);
fs.WriteByte(b);
h = string.Empty;
}
}
}
Note that both StreamReader
and File.Create
(that returns a FileStream
) do some buffering, so no explicit buffering is needed. My hands are quivering because they want to remove the string h
buffer and do the parsing hex digit by hex digit directly in the byte b
. But I'll try to not overcomplicate the code :-)