Valhalla Legends Archive

Programming => General Programming => .NET Platform => Topic started by: c0ol on September 22, 2004, 03:09 AM

Title: dword (UInt32) buffers?
Post by: c0ol on September 22, 2004, 03:09 AM
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.
Title: Re:dword (UInt32) buffers?
Post by: MyndFyre on September 22, 2004, 05:02 AM

// 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;
    }
 }
}
Title: Re:dword (UInt32) buffers?
Post by: c0ol on September 22, 2004, 12:49 PM
mm pointers in c#, interesting ;)
Title: Re:dword (UInt32) buffers?
Post by: K on September 22, 2004, 04:24 PM
You could also intialize a System.IO.MemoryStream containing the bytes and read it from there.

BTW, won't that code complain here:

fixed(uint* pnUint = bytes)

that bytes is not a pointer to a uint?

I seem to recall having that problem; the next thing I tried was:

fixed(uint* p = (uint*)bytes)

and it complained that you cannot have a typecast insided a fixed() statement, so I ended up doing:


fixed(byte* bTmp = bytes)
{
   uint* p = (uint*)bTmp;
}


Or maybe I'm crazy  :P
Title: Re:dword (UInt32) buffers?
Post by: c0ol on September 22, 2004, 05:04 PM
well thanks guys, i wasnt even aware you could do pointers in c# lol.  This helps alot!
Title: Re:dword (UInt32) buffers?
Post by: Skywing on September 22, 2004, 05:07 PM
Quote from: c0ol on September 22, 2004, 05:04 PM
well thanks guys, i wasnt even aware you could do pointers in c# lol.  This helps alot!
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).
Title: Re:dword (UInt32) buffers?
Post by: MyndFyre on September 22, 2004, 05:49 PM
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.  ;)