blah blah

UUID ByteArray

Java 에서 UUID 값을 바이트 배열로 변환. 바이트 배열값을 UUID 로 변환하는 기능을 stackoverflow 에 올라온 여러가지 글들을 참고해서 간단히 짜보았습니다.

 

import java.nio.ByteBuffer;
import java.util.UUID;

import com.google.common.primitives.Longs;

 

public class Uuids {
    public static byte[] toByteArray(UUID uuid) {
        ByteBuffer buff = ByteBuffer.wrap(new byte[16]);
        buff.putLong(uuid.getMostSignificantBits());
        buff.putLong(uuid.getLeastSignificantBits());

        return buff.array();
}

public static UUID fromByteArray(byte[] byteArray) {

        long mostSigBits = Longs.fromByteArray(byteArray);
        long leastSigBits = 0;
        for (int i = 8; i < 16; i++)
            leastSigBits = (leastSigBits << 8) | (byteArray[i] & 0xff);

 

        return new UUID(mostSigBits, leastSigBits);
}

 

테스트

@Test
public void testFromByteArray() {
    UUID u = UUID.randomUUID();

    byte[] bt = Uuids.toByteArray(u);

    assertEquals(u, Uuids.fromByteArray(bt));
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s