C# Unsafe Bug



I was writing some routines which could do bitwise boolean operations
on byte arrays, and I ran into what I think is a bug with C#'s unsafe
code. I am pasting a console application below. Can anyone give an
explanation, or has this type of problem been reported already?
Thanks.

using System;
using System.Collections.Generic;
using System.Text;

namespace UnsafeBug
{
class Program
{
static void Main(string[] args)
{
byte[] dest = new byte[] { 0x01, 0xff };
byte[] sdata1 = new byte[] { 0x01, 0xff };
UnsafeOr(sdata1, dest, dest, 7);

for (int ii = 0; ii < dest.Length; ii++)
{
Console.WriteLine("Byte {0} = 0x{1:X2}", ii + 1, dest[ii]);
}
Console.WriteLine("Hit Enter to quit..."); Console.ReadLine();
}

// OR's together 2 byte arrays into 'dest' without touching the
first few bits of 'dest'.
// it is allowed for sources/destinations to be the same.
static void UnsafeOr(byte[] src1, byte[] src2, byte[] dest, int
firstBit)
{
byte mask = (byte)(0x80 >> firstBit);
int nbytes = Math.Min(Math.Min(src1.Length, src2.Length),
dest.Length);
unsafe
{
fixed (byte* s1data = &src1[0], s2data = &src2[0], ddata =
&dest[0])
{
byte* s1ptr = s1data;
byte* s2ptr = s2data;
byte* dptr = ddata;

#if false
// this version works
byte val = (byte)(*dptr & ~mask);
*dptr++ = (byte)(val | ((*s1ptr++ | *s2ptr++)&mask));
#else
// this version does not work
*dptr++ = (byte)((*dptr & ~mask) | ((*s1ptr++ |
*s2ptr++)&mask));
#endif
for (int ii = 1; ii < nbytes; ii++)
{
*dptr++ = (byte)(*s1ptr++ | *s2ptr++);
}
}
}
}
}
}

.



Relevant Pages

  • Re: How to compare two byte arrays ?
    ... what happens if the arrays doesn't match in the first few bytes of the ... With byte arrays of size 20 the unsafe version is still twice as fast. ... and/or if the comparisons fail in the first ... few bytes the advantage turns to the safe version. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: [PATCH 2/2] tracing: identify which executable object the userspace address belongs to
    ... it's generally unsafe to look up a vma and use it without having ... Bug: it is unsafe to look up a task and then drop the RCU lock and use ...
    (Linux-Kernel)
  • Re: C# Unsafe Bug
    ... I am pasting a console application below. ... I don't believe this is a bug, and I don't believe it has anything to ... do with unsafe code. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: pointer bug
    ... > I think I've found a bug on Microsoft Visual C# or maybe on the .NET ... > Framework itself... ... unsafe code isn't guaranteed to throw an exception when you do bad things. ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: partial arrays???
    ... The 'CopyTo' method on arrays might be what you want. ... Other than that, you could use 'unsafe' code in C#, but nobody really wants ... C++ to Java ...
    (microsoft.public.dotnet.languages.csharp)