In a Java method that receives a java.util.UUID Object, I would like to display this object as a string in the .NET/C# format (CSUUID).
Currently I am only able to display it in the Java format (JUUID) :
static String GetStringFromUuid (java.util.UUID myUuid){
return myUuid.toString();
}
Current output: "46c7220b-1f25-0118-f013-03bd2c22d6b8"
Desired output: "1f250118-220b-46c7-b8d6-222cbd0313f0"
Context:
The UUID is stored in MongoDB and is retrieved with the Java ETL program Talend (tMongoDBInput component).
In the Java program, the method already receives the UUID as a java.util.UUID Object (I do not have directly access to the BinData in the program).
Guid is represented by 16 bytes. For various reasons, both Java and .NET do not just print those bytes in order when you call toString
. For example, if we look at base-64 encoded guid from your question:
GAElHwsix0a41iIsvQMT8A==
In hex form it will look like this:
18-01-25-1f-0b-22-c7-46-b8-d6-22-2c-bd-03-13-f0
Java toString
produces this (if we format as above):
46-c7-22-0b-1f-25-01-18-f0-13-03-bd-2c-22-d6-b8
.NET ToString
produces this:
1f-25-01-18-22-0b-46-c7-b8-d6-22-2c-bd-03-13-f0
If you look at this for some time - you will notice that both java and .NET strings represent the same 16 bytes, but positions of those bytes in output string are different. So to convert from java representation to .NET you just need to reorder them. Sample code (I don't know java, so probably it could be done in a better way, but still should achieve the desired result):
static String GetStringFromUuid (java.util.UUID myUuid){
byte[] bytes = new byte[16];
// convert uuid to byte array
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.putLong(myUuid.getMostSignificantBits());
bb.putLong(myUuid.getLeastSignificantBits());
// reorder
return String.format("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
bytes[4],bytes[5],bytes[6],bytes[7],
bytes[2],bytes[3],bytes[0],bytes[1],
bytes[15],bytes[14],bytes[13],bytes[12],
bytes[11],bytes[10],bytes[9],bytes[8]);
}
We can just keep the GUID as string, if the c# function is receiving the string and it needs to be displayed or sent to some service as string
Just in case if you want to parse it. You can use the link for GUID parsing logic example
For creating new GUID in C#, use
var guid = System.Guid.NewGuid();
var guidString = guid.ToString();
For creating new UUID in Java, use
UUID uuid = java.util.UUID.randomUUID();
String uuidString = uuid.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With