C# 在C中将.mjpeg文件的十六进制数据保存为.mjpeg格式的文件
我有一个充满十六进制数据的文本文件,比如FFD8FE00。。一个.mjpeg格式的文件。我必须用一个转换器来播放它。 因此,我试图用以下行将数据写入.mjpeg文件:C# 在C中将.mjpeg文件的十六进制数据保存为.mjpeg格式的文件,c#,arrays,codec,mjpeg,C#,Arrays,Codec,Mjpeg,我有一个充满十六进制数据的文本文件,比如FFD8FE00。。一个.mjpeg格式的文件。我必须用一个转换器来播放它。 因此,我试图用以下行将数据写入.mjpeg文件: string myData = File.ReadAllText("hexData.txt"); string newData; int remainder = myData.Length%500; byte[] data_toWrite=newByte[250]; for(int i=0;i<myData.Lengt
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;
}
但我不能让它发挥。我不知道我错在哪里。我尝试将新数据转换为ascii码,然后转换为字节数组,但也失败了
任何想法,非常感谢
凯恩这个
File.WriteAllBytes("video.mjpeg",data_toWrite);
每次都覆盖文件,而不是追加
我相信可以编写更好的代码,但这应该足够了:
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;
}
}
}
请注意,返回FileStream的StreamReader和File.Create都会执行一些缓冲,因此不需要显式缓冲。我的手在颤抖,因为他们想删除字符串h缓冲区,直接在字节b中逐个解析十六进制数字。但我会尽量不使代码过于复杂:-真是太棒了!它工作得很好。非常感谢!!: