Java中的Base64指导 [英] Guid to Base64 in Java

查看:57
本文介绍了Java中的Base64指导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将Guid转换为C#中的Base64:

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());

输出

thufvo5cfUCFo9XvMfIbTQ ==

thufvo5cfUCFo9XvMfIbTQ==

当我尝试使用以下命令在Java中执行相同操作时:

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());

不同的输出

vp8btlyOQH2Fo9XvMfIbTQ ==

vp8btlyOQH2Fo9XvMfIbTQ==

我在Java代码中做错了什么?如何获得与C#相同的结果?

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

推荐答案

结构有些不同,但是在字节数组的第一部分交换一些字节可以解决您的问题.

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

这篇关于Java中的Base64指导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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