Is there any way to generate a UUID in Java that is identical to that of the one generated in C#?

前端 未结 1 817
走了就别回头了
走了就别回头了 2021-02-06 01:35

I\'m porting a C# script into Spark (Scala) and I\'m running into an issue with UUID generation in Scala vs GUID generation in C#.

Is there any way to generate

相关标签:
1条回答
  • 2021-02-06 01:49

    TL;DR

    If you want your C# and your Java to act exactly the same way (and you are happy with the existing C# behaviour), you'll need to manually re-order some of the bytes in uuid_bytes (i.e. swap some of the entries you identified as out of order).

    Additionally, you should not use:

    UUID.nameUUIDFromBytes(to_encode.trim().getBytes())
    

    But instead use:

    public static String getGuidFromByteArray(byte[] bytes) {
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        long high = bb.getLong();
        long low = bb.getLong();
        UUID uuid = new UUID(high, low);
        return uuid.toString();
    }
    

    Shamelessly stolen from https://stackoverflow.com/a/24409153/34092 :)

    Additional Background

    In case you weren't aware, when dealing with C#'s GUIDs:

    Note that the order of bytes in the returned byte array is different from the string representation of a Guid value. The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the last two-byte group and the closing six-byte group is the same. The example provides an illustration.

    And:

    The order of hexadecimal strings returned by the ToString method depends on whether the computer architecture is little-endian or big-endian.

    In your C#, rather than using:

    Console.WriteLine("Guid: {0}", guid);
    

    you may want to consider using:

    Console.WriteLine(BitConverter.ToString(guid.ToByteArray()));
    

    Your existing code calls ToString behind the scenes. Alas, ToString and ToByteArray do not return the bytes in the same order.

    0 讨论(0)
提交回复
热议问题