gpt4 book ai didi

java - Java 中的 Base64 指南

转载 作者:行者123 更新时间:2023-12-01 14:33:57 24 4
gpt4 key购买 nike

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

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

输出

thufvo5cfUCFo9XvMfIbTQ==



当我尝试使用以下方法在 Java 中执行相同操作时:
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==



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

最佳答案

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

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 - Java 中的 Base64 指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com