G
Guest
I need to store a uint in an array of bytes. Doing it old fashioned
style works:
byte[] b=new byte[8];
ulong ul = 1;
for(int j=0; j<8; j++)
{
--- obviously I could (and did) optimize the code inside the loop
--- I just wanted to keep my example simple
b[7 - j] = (byte)((ul & bmask) >> j*8);
bmask = bmask << 8;
}
It gives me exactly what I need:
b[0] = 0;
b[1] = 0;
(snip)
b[7] = 1;
I was trying to use MemoryStream and BinaryWriter and see how fast it
performs:
MemoryStream ms = new MemoryStream(16);
BinaryWriter br = new BinaryWriter(ms);
for(ulong i=1; i<3; i++)
{
br.Write(i);
}
byte[] b = ms.ToArray();
Unfortunately the order of bytes is not what I want:
b[0] = 1;
b[1] = 0;
b[2] = 0;
(snip)
b[7] = 0;
Is there any way to use canned classes like MemoryStream and
BinaryWriter and get the results that I got from my first snippet? The
reason I am asking is simple: canned classes might perform faster than
my homemade solution.
style works:
byte[] b=new byte[8];
ulong ul = 1;
for(int j=0; j<8; j++)
{
--- obviously I could (and did) optimize the code inside the loop
--- I just wanted to keep my example simple
b[7 - j] = (byte)((ul & bmask) >> j*8);
bmask = bmask << 8;
}
It gives me exactly what I need:
b[0] = 0;
b[1] = 0;
(snip)
b[7] = 1;
I was trying to use MemoryStream and BinaryWriter and see how fast it
performs:
MemoryStream ms = new MemoryStream(16);
BinaryWriter br = new BinaryWriter(ms);
for(ulong i=1; i<3; i++)
{
br.Write(i);
}
byte[] b = ms.ToArray();
Unfortunately the order of bytes is not what I want:
b[0] = 1;
b[1] = 0;
b[2] = 0;
(snip)
b[7] = 0;
Is there any way to use canned classes like MemoryStream and
BinaryWriter and get the results that I got from my first snippet? The
reason I am asking is simple: canned classes might perform faster than
my homemade solution.