将Java UUID对象转换为.NET GUID字符串 [英] Transforming a Java UUID object to a .NET GUID string

查看:122
本文介绍了将Java UUID对象转换为.NET GUID字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在接收java.util.UUID对象的Java方法中,我想将此对象显示为.NET/C#格式(CSUUID)的字符串.

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).

目前,我只能以Java格式(JUUID)显示它:

Currently I am only able to display it in the Java format (JUUID) :

static String GetStringFromUuid (java.util.UUID myUuid){
    return myUuid.toString();
}

电流输出:"46c7220b-1f25-0118-f013-03bd2c22d6b8"

所需的输出:"1f250118-220b-46c7-b8d6-222cbd0313f0"


上下文:

  • UUID存储在MongoDB中,并通过Java ETL程序Talend(tMongoDBInput组件)进行检索.

  • The UUID is stored in MongoDB and is retrieved with the Java ETL program Talend (tMongoDBInput component).

在Java程序中,该方法已经将UUID作为java.util.UUID对象接收(我无法直接访问程序中的BinData).

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).

推荐答案

向导由16个字节表示.由于各种原因,当您调用toString时,Java和.NET都不会仅按顺序打印这些字节.例如,如果我们从您的问题中查看以base-64编码的guid:

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生成此代码(如果我们按照上述格式设置):

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产生此结果:

.NET ToString produces this:

1f-25-01-18-22-0b-46-c7-b8-d6-22-2c-bd-03-13-f0

如果您花了一段时间看-您会注意到java和.NET字符串都表示相同的16个字节,但是这些字节在输出字符串中的位置不同.因此,要将Java表示形式转换为.NET,您只需要对其重新排序即可.示例代码(我不懂Java,所以可能可以用更好的方法来完成,但仍然应该达到预期的结果):

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]);
}

这篇关于将Java UUID对象转换为.NET GUID字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆