Skip to content

Instantly share code, notes, and snippets.

@sevaa
Last active March 2, 2025 19:06
Show Gist options
  • Save sevaa/6d0807988884b2b15c2f977a99c81332 to your computer and use it in GitHub Desktop.
Save sevaa/6d0807988884b2b15c2f977a99c81332 to your computer and use it in GitHub Desktop.
Java/Android UUID (GUID) to bytes in a Windows compatible way
package com.example;
import java.util.UUID;
class UUIDUtil
{
static private final int []s_Shuffle = {32, 40, 48, 56, 16, 24, 0, 8};
public static void UUIDToBytes(UUID g, byte[]b, int offset)
{
int i;
long hi = g.getMostSignificantBits(), lo = g.getLeastSignificantBits();
for(i=0;i<8;i++)
{
b[offset + i] = (byte) (hi >> s_Shuffle[i]);
b[offset + 8 + i] = (byte) (lo >> (56 - 8*i));
}
}
public static byte[] UUIDToBytes(UUID g)
{
byte []b = new byte[16];
UUIDToBytes(g, b, 0);
return b;
}
public static UUID bytesToUUID(byte []b, int offset)
{
int i;
long hi = 0, lo = 0;
for(i=0;i<8;i++)
{
hi |= (((long)b[offset + i]) & 0xff) << s_Shuffle[i];
lo |= (((long)b[offset + 8 + i]) & 0xff) << (56 - 8*i);
}
return new UUID(hi, lo);
}
public static UUID bytesToUUID(byte []b)
{
return bytesToUUID(b, 0);
}
}
@sevaa
Copy link
Author

sevaa commented Mar 2, 2025

Companion gist to this blog post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment