0

I need my code to do something like this - Somewhere in the code num gets a value and after that i want to read from file EXACTLY as bytes is the number num.

For example: If num is 39382 i need to read 39382 bytes and place them into byte[] buffer;

Before I had something like this:

ushort num = 0;
//....  num get some value;
byte[] buffer = bRead.ReadBytes(num);

Now I have to change it so that num is a UInt32, but then ReadBytes doesn't work(because it wants int32). It's possible 'num' to exceeds int32. I fixed it like this:

byte[] buffer = new byte[num];
for (int j = 0; j < num; j++)
{
    buffer[j] = bRead.ReadByte();
}

and it works but I am wondering is that the best way of doing it? Or there is another?

Georgi
  • 519
  • 4
  • 19
  • Warning: allocating a >2GB array will only work on .NET 4.5 64bit with `gcAllowVeryLargeObjects` set to true. You might want to work with a `FileStream` or equivalent instead. – Julien Lebosquain Jan 20 '14 at 09:19
  • And thats one of the reasons i want to change it with better one. – Georgi Jan 20 '14 at 10:32

2 Answers2

0

If you're sure that num won't go beyond the int32 max you can use the following:

UInt32 num = 0;
//....  num get some value;
bRead.ReadBytes(checked((int)num));

This will throw an OverflowException if num goes beyond the signed 32 bit max.

Vincent
  • 1,459
  • 15
  • 37
0

You can use:

public static ushort ToUInt32(
    byte[] value,
    int startIndex
)

you specify the source array and the position where the encoded number starts. If your byte array contains a single number, startIndex will be 0, and the length must be at least 4.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115