c# - 在 C# 中将 .mjpeg 文件的十六进制数据保存为 .mjpeg 格式的文件
问题描述
我有一个填充了 .mjpeg 格式文件的十六进制数据(如“FFD8FE00..”)的文本文件。我必须用转换器玩它。因此,我正在尝试使用以下几行将数据写入 .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.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;
}
但我无法让它发挥作用。我不知道我错在哪里。我试图将 newData 转换为 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;
}
}
}
请注意,StreamReader
and File.Create
(返回 a FileStream
)都做了一些缓冲,因此不需要显式缓冲。我的手在颤抖,因为他们想删除string h
缓冲区并直接在byte b
. 但我会尽量不要使代码过于复杂:-)
推荐阅读
- c# - Bitmap.Save 出现 Null 异常的错误,但它显然已实例化
- django - Django 上的社交网络登录失败,回调 url 不匹配
- java - 具有多个视图的 Recyclerview,删除 addTextChangedListener() 不起作用
- postgresql - Postgres json聚合函数调用不能嵌套
- android - 在 Progressive Web App 上可以进行屏幕旋转,但在 Native android 应用程序上则不行
- amazon-web-services - Apache Airflow S3ListOperator 未列出文件
- java - SAX Parser 不显示多个相同的标签
- json - 使用 jq 将 JSON 文档中的单个 JSON 对象转换为数组
- reactjs - 如果我的前端在生产中崩溃,Chrome 会显示什么?
- github - 如何将整个分支移动到主分支