开发者

C# Adding data to an array?

My code below reads a file offset and writes the hexadecimal values to the "MyGlobals.Hexbytes" variable .... How could I get it to write into an array instead?

Many Thanks

MyGlobals.Mapsettings_filepath = "C:\\123.cfg";

///////////////////////////// Read in the selected //////////////

BinaryReader br = new BinaryReader(File.OpenRead(MyGlobals.Mapsettings_filepath),
System.Text.Encoding.BigEndianUnicode);

for (int a = 32; a <= 36; a++)
{
    br.BaseStream.Position = a;
    MyGlobals.Hexbytes += br.ReadByte().ToString("X2") + ",";开发者_如何学Go
}


Make MyGlobals.Hexbytes to be List<string> instead then:

br.BaseStream.Position = a;
MyGlobals.Hexbytes.Add(br.ReadByte().ToString("X2"));

Later to display it, use String.Join like this:

string myBytes = string.Join(",", MyGlobals.Hexbytes.ToArray());


Array is a fixed size structure, so you cannot add elements to it.

If you know the size in advance (as it seems in your example) you can instanciate it and then add elements to the pre-allocated slots:

e.g.

string[] byteStrings = new string[5]; // 36 - 32 + 1 = 5 

for (int a = 32; a <= 36; a++)
{
   br.BaseStream.Position = a;
   byteStrings[a - 32] = br.ReadByte().ToString("X2");
}

But it's much easier to use a dynamically-resizable collection, like List<T>:

var byteStrings = new List<string>();
for (int a = 32; a <= 36; a++)
{
   br.BaseStream.Position = a;
   byteStrings.Add(br.ReadByte().ToString("X2"));
}


Assuming MyGlobals.Hexbytes, which is likely, you could leave your code the way it is and add this in the end:

var myarray = MyGlobals.Hexbytes.Split(',');

myarray is an array of string.


You should first define the size of the array and thus you should first set its size and then populate it:

string[] array = new string[5];

for (int a = 32; a <= 36; a++)
{
    br.BaseStream.Position = a;
    array[a - 32] += br.ReadByte().ToString("X2");
}

Here is how to read 4 bytes at once:

            BinaryReader reader = ....;
...
            byte[] buffer = new byte[4];
            reader.Read(buffer, 0, 4);

...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜