Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
Unsafe.As from byte array to ulong array

I'm currently looking at porting my metro hash implementon to use C#7 features, as several parts might profit from ref locals to improve performance. The hash does the calculations on a ulong[4] array, but the result is a 16 byte array. Currently I'm copying the ulong array to the result byte buffer, but this takes a bit of time. So i'm wondering if System.Runtime.CompilerServices.Unsafe is safe to use here:

var result = new byte[16];
ulong[] state = Unsafe.As<byte[], ulong[]>(ref result);
ref var firstState = ref state[0];
ref var secondState = ref state[1];
ulong thirdState = 0;
ulong fourthState = 0;

The above code snippet means that I'm using the result buffer also for parts of my state calculations and not only for the final output.

My unit tests are successful and according to benchmarkdotnet skipping the block copy would result in a 20% performance increase, which is high enough for me to find out if it is correct to use it.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

In current .NET terms, this would be a good fit for Span<T>:

Span<byte> result = new byte[16];
Span<ulong> state = MemoryMarshal.Cast<byte, ulong>(result);

This enforces lengths etc, while having good JIT behaviour and not requiring unsafe. You can even stackalloc the original buffer (from C# 7.2 onwards):

Span<byte> result = stackalloc byte[16];
Span<ulong> state = MemoryMarshal.Cast<byte, ulong>(result);

Note that Span<T> gets the length change correct; it is also trivial to cast into a Span<Vector<T>> if you want to use SIMD for hardware acceleration.

about 4 years ago · Santiago Trujillo Denunciar

0

What you're doing seems fine, just be careful because there's nothing to stop you from doing this:

byte[] x = new byte[16];
long[] y = Unsafe.As<byte[], long[]>(ref x);

Console.WriteLine(y.Length); // still 16

for (int i = 0; i < y.Length; i++)
    Console.WriteLine(y[i]); // reads random memory from your program, could cause crash
about 4 years ago · Santiago Trujillo Denunciar

0

C# supports "fixed buffers", here's the kind of thing we can do:

    public unsafe struct Bytes
    {
        public fixed byte bytes[16];
    }

then

    public unsafe static Bytes Convert (long[] longs)
    {
        fixed (long * longs_ptr = longs)
              return *((Bytes*)(longs_ptr));
    }

Try it. (1D arrays of primitive types in C# are always stored as a contiguous block of memory which is why taking the address of the (managed) arrays is fine).

You could also even return the pointer for more speed:

    public unsafe static Bytes * Convert (long[] longs)
    {
        fixed (long * longs_ptr = longs)
        return ((Bytes*)(longs_ptr));
    }

and manipulate/access the bytes as you want.

        var s = Convert(longs);
        var b = s->bytes[0];
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda