Guid to Base64 in Java

99封情书 提交于 2019-12-13 01:13:10

问题


I am converting a Guid to Base64 in C# using the following code:

var id = Guid.Parse("be9f1bb6-5c8e-407d-85a3-d5ef31f21b4d");
var base64=Convert.ToBase64String(id.ToByteArray());

Output

thufvo5cfUCFo9XvMfIbTQ==

When I try to do the same in Java using the following:

java.util.Base64.Encoder encoder=Base64.getEncoder();
UUID uuid = UUID.fromString("be9f1bb6-5c8e-407d-85a3-d5ef31f21b4d");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
encoder.encodeToString(bb.array());

Different output

vp8btlyOQH2Fo9XvMfIbTQ==

What I am doing wrong in my Java code? How can I get the same result I am getting using C#?


回答1:


The structure is a bit different, but swapping some bytes in the first part of the byte array fixes your problem.

java.util.Base64.Encoder encoder= Base64.getEncoder();
UUID uuid = UUID.fromString("be9f1bb6-5c8e-407d-85a3-d5ef31f21b4d");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());

byte[] uuid_bytes = bb.array();
byte[] guid_bytes = Arrays.copyOf(uuid_bytes,uuid_bytes.length);

guid_bytes[0] = uuid_bytes[3];
guid_bytes[1] = uuid_bytes[2];
guid_bytes[2] = uuid_bytes[1];
guid_bytes[3] = uuid_bytes[0];
guid_bytes[4] = uuid_bytes[5];
guid_bytes[5] = uuid_bytes[4];
guid_bytes[6] = uuid_bytes[7];
guid_bytes[7] = uuid_bytes[6];

String result = encoder.encodeToString(guid_bytes);


来源:https://stackoverflow.com/questions/51609674/guid-to-base64-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!