Valhalla Legends Forums Archive | .NET Platform | dword (UInt32) buffers?

AuthorMessageTime
c0ol
I am reading file data in using a file stream. I am reading this data into a Byte array. I would like to access this data in terms of UInt32s. In c++ i would simply typecast the buffer, but in c# this does not seem to be the solution. How can I access this array in terms of UInt32s without copying the data into a UInt32 array with Buffer.BlockCopy(); this method would be far too slow for my needs.
September 22, 2004, 8:09 AM
Myndfyr
[code]
// compile with /unsafe
private unsafe void doSomethingWithUint32s(byte[] bytes) {
int nCurPos = 0;
fixed (uint *pnUint = bytes)
{
// use old-fashioned pointer manipulation here.
while (bytes.Length - nCurPost >= 4)
{
// do your thing regarding pnUint.
pnUint += sizeof(uint); // same as += 4;
nCurPos += 4;
}
}
}
[/code]
September 22, 2004, 10:02 AM
c0ol
mm pointers in c#, interesting ;)
September 22, 2004, 5:49 PM
K
You could also intialize a System.IO.MemoryStream containing the bytes and read it from there.

BTW, won't that code complain here:
[code]
fixed(uint* pnUint = bytes)
[/code]
that bytes is not a pointer to a uint?

I seem to recall having that problem; the next thing I tried was:
[code]
fixed(uint* p = (uint*)bytes)
[/code]
and it complained that you cannot have a typecast insided a fixed() statement, so I ended up doing:

[code]
fixed(byte* bTmp = bytes)
{
uint* p = (uint*)bTmp;
}
[/code]

Or maybe I'm crazy :P
September 22, 2004, 9:24 PM
c0ol
well thanks guys, i wasnt even aware you could do pointers in c# lol. This helps alot!
September 22, 2004, 10:04 PM
Skywing
[quote author=c0ol link=board=37;threadid=8794;start=0#msg81448 date=1095890648]
well thanks guys, i wasnt even aware you could do pointers in c# lol. This helps alot!
[/quote]
This isn't always desireable, though. Your images will be marked "unsafe" / "unverified", so if you are planning to make something that runs in, say, browsers (e.g. like a Java applet) then you would probably not want to use pointers (as "untrusted" code cannot do "unsafe" things, IIRC).
September 22, 2004, 10:07 PM
Myndfyr
That's a good point K, heh, sorry I put that up while at work w/o a compiler available. ;)

Also, you could just use BitConvert.ToUInt32(bytes, i); and increment i by four every iteration. ;)
September 22, 2004, 10:49 PM

Search