gpt4 book ai didi

java - GUID 到 ByteArray

转载 作者:IT老高 更新时间:2023-10-28 21:17:02 25 4
gpt4 key购买 nike

我刚刚编写了这段代码来将 GUID 转换为字节数组。任何人都可以在其中挖洞或提出更好的建议吗?

 public static byte[] getGuidAsByteArray(){

UUID uuid = UUID.randomUUID();
long longOne = uuid.getMostSignificantBits();
long longTwo = uuid.getLeastSignificantBits();

return new byte[] {
(byte)(longOne >>> 56),
(byte)(longOne >>> 48),
(byte)(longOne >>> 40),
(byte)(longOne >>> 32),
(byte)(longOne >>> 24),
(byte)(longOne >>> 16),
(byte)(longOne >>> 8),
(byte) longOne,
(byte)(longTwo >>> 56),
(byte)(longTwo >>> 48),
(byte)(longTwo >>> 40),
(byte)(longTwo >>> 32),
(byte)(longTwo >>> 24),
(byte)(longTwo >>> 16),
(byte)(longTwo >>> 8),
(byte) longTwo
};
}

在 C++ 中,我记得能够做到这一点,但我想在 Java 中没有办法通过内存管理和所有功能做到这一点?:

    UUID uuid = UUID.randomUUID();

long[] longArray = new long[2];
longArray[0] = uuid.getMostSignificantBits();
longArray[1] = uuid.getLeastSignificantBits();

byte[] byteArray = (byte[])longArray;
return byteArray;

编辑

如果你想生成一个完全随机的 UUID 作为不符合任何官方类型的字节,这将起作用并且浪费 10 fewer bits比 UUID.randomUUID() 生成的类型 4 UUID:

    public static byte[] getUuidAsBytes(){
int size = 16;
byte[] bytes = new byte[size];
new Random().nextBytes(bytes);
return bytes;
}

最佳答案

我会依赖内置功能:

ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();

或者类似的,

ByteArrayOutputStream ba = new ByteArrayOutputStream(16);
DataOutputStream da = new DataOutputStream(ba);
da.writeLong(uuid.getMostSignificantBits());
da.writeLong(uuid.getLeastSignificantBits());
return ba.toByteArray();

(注意,未经测试的代码!)

关于java - GUID 到 ByteArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983065/

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