如何将 Guid.ToByteArray() 的以下 .net 用法转换为 Java?
var g= Guid.Parse("9836f2b9-ba8c-42a6-b884-2e9eed9fb95a");
var ga = g.ToByteArray();
返回.Net Byte数组
ga= [185,242,54,152,140,186,166,66,184,132,46,158,237,159,185,90]
Java 中的尝试(与 .Net 数组不匹配)
UUID uuid = UUID.fromString("9836f2b9-ba8c-42a6-b884-2e9eed9fb95a");
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
byte[] ga= bb.array();
返回 Java 字节数组
ga= [-72,-124,46,-98,-19,-97,-71,90,-104,54,-14,-71,-70,-116,66,-90]
更新了解决方案 Guid to Base64 in Java
UUID uuid = UUID.fromString("9836f2b9-ba8c-42a6-b884-2e9eed9fb95a");
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];
byte[] ga= guid_bytes;
最佳答案
问题的替代解决方案 -
public static byte[] getByteArrayFromUUID(UUID uuid) {
ByteBuffer mostSignificantBitsByteBuffer = ByteBuffer.allocate(Long.BYTES)
.putLong(uuid.getMostSignificantBits());
return ByteBuffer.allocate(Long.BYTES * 2)
.order(ByteOrder.LITTLE_ENDIAN)
.putShort(mostSignificantBitsByteBuffer.getShort(2))
.putShort(mostSignificantBitsByteBuffer.getShort(0))
.putShort(mostSignificantBitsByteBuffer.getShort(4))
.putShort(mostSignificantBitsByteBuffer.getShort(6))
.order(ByteOrder.BIG_ENDIAN)
.putLong(uuid.getLeastSignificantBits())
.array();
}
关于java - Java 中的 .Net Guid.ToByteArray() 相当于什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60424189/