sql >> Base de Datos >  >> RDS >> Oracle

Convierta de RAW(16) de Oracle a GUID de .NET

Si observa los valores involucrados (en pares) de dígitos hexadecimales, puede ver que los últimos 7 bytes son los mismos en ambos casos, pero los primeros 9 están un poco cambiados.

Partiendo de su ejemplo, pero reescribiendo cada par en .NET como 00, 11, 22, etc. y cambiando también el byte relevante de Oracle, obtenemos:

  • .NET:

    00112233445566778899AABBCCDDEEFF
    
  • Oráculo:

    33221100554477668899AABBCCFFEEFF
    

Por lo tanto, debería ser bastante fácil escribir código para cambiar los bytes relevantes. (Estoy bastante seguro de que escribí un código para hacer esto en un trabajo anterior, de hecho).

Para cambiar los bytes, solo querrá llamar a Guid.ToByteArray() y new Guid(byte[]) para volver a un Guid .

EDITAR:Da la casualidad de que el cambio de ronda anterior es exactamente cuál es el Guid constructor hace cuando le pasas una matriz de bytes:

using System;
using System.Linq;

class Test
{
    static void Main()
    {
        byte[] bytes = Enumerable.Range(0, 16)
                                 .Select(x => x * 16 + x)
                                 .Select(x => (byte) x)
                                 .ToArray();

        Console.WriteLine(BitConverter.ToString(bytes).Replace("-", ""));
        Console.WriteLine(new Guid(bytes).ToString().Replace("-", ""));
    }
}

Impresiones:

00112233445566778899AABBCCDDEEFF
33221100554477668899aabbccddeeff

Eso bien puede hacer que sea considerablemente más simple realizar el cambio... ¿cómo obtuvo los valores para empezar? ¿Es simplemente "cómo se muestran en Oracle"?

EDITAR:Bien, aquí hay un par de funciones de conversión:si tiene los datos como texto, se convertirán en cada dirección...

using System;
using System.Linq;

class Test
{
    static void Main()
    {
        string oracle = "329DD817216CD6429B989F5201288DBF";
        string dotNet = "17D89D326C2142D69B989F5201288DBF";

        Console.WriteLine(oracle == DotNetToOracle(dotNet));
        Console.WriteLine(dotNet == OracleToDotNet(oracle));
    }

    static string OracleToDotNet(string text)
    {
        byte[] bytes = ParseHex(text);
        Guid guid = new Guid(bytes);
        return guid.ToString("N").ToUpperInvariant();
    }

    static string DotNetToOracle(string text)
    {
        Guid guid = new Guid(text);
        return BitConverter.ToString(guid.ToByteArray()).Replace("-", "");
    }

    static byte[] ParseHex(string text)
    {
        // Not the most efficient code in the world, but
        // it works...
        byte[] ret = new byte[text.Length / 2];
        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = Convert.ToByte(text.Substring(i * 2, 2), 16);
        }
        return ret;
    }

}