我有一个字节数组,我想从中获取值到变量中。 我知道值格式,如字符串、无符号整数等。
byte[] buffer = File.ReadAllBytes("binarydata.bin");
string value1 = ???
uint16 value2 = ???
string value3 = ???
uint32 value4 = ???
如何分配值?我知道第一个值是一个 8 的字符串,我知道第二个值是一个有符号的 16 位 int,第三个值是一个 12 的字符串,第四个是一个无符号的 32 位 int。
最佳答案
您可以简单地使用 BinaryReader
Reads primitive data types as binary values in a specific encoding
示例
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
var aspectRatio = reader.ReadSingle();
var tempDirectory = reader.ReadString();
var autoSaveTime = reader.ReadInt32();
var showStatusBar = reader.ReadBoolean();
Console.WriteLine("Aspect ratio set to: " + aspectRatio);
Console.WriteLine("Temp directory is: " + tempDirectory);
Console.WriteLine("Auto save time set to: " + autoSaveTime);
Console.WriteLine("Show status bar: " + showStatusBar);
}
从 xanatos 更新
ReadString 从当前流中读取一个字符串。该字符串以长度为前缀,一次编码为 7 位整数。
关于C#字节数组转化为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638440/