GUID到ByteArray [英] GUID to ByteArray
本文介绍了GUID到ByteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚编写此代码以将GUID转换为字节数组。任何人都可以在其中拍摄任何漏洞或提出更好的建议吗?
I just wrote this code to convert a GUID into a byte array. Can anyone shoot any holes in it or suggest something better?
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进行内存管理和所有操作的方法吗?:
In C++, I remember being able to do this, but I guess theres no way to do it in Java with the memory management and all?:
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比特由UUID.randomUUID()生成的类型4 UUID:
Edit
If you want to generate a completely random UUID as bytes that does not conform to any of the official types, this will work and wastes 10 fewer bits than type 4 UUIDs generated by UUID.randomUUID():
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();
(注意,未经测试的代码!)
(Note, untested code!)
这篇关于GUID到ByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文