关于uuid类型的转换

对于没有分隔符的uuid字符串转换方式如下:

	public static UUID fromStringWhitoutHyphens(String str) {
		if (str.length() != 32) {
			throw new IllegalArgumentException("Invalid UUID string: " + str);
		}
		String s1 = "0x" + str.substring(0, 8);
		String s2 = "0x" + str.substring(9, 12);
		String s3 = "0x" + str.substring(13, 16);
		String s4 = "0x" + str.substring(17, 20);
		String s5 = "0x" + str.substring(21, 32);

		long mostSigBits = Long.decode(s1).longValue();
		mostSigBits <<= 16;
		mostSigBits |= Long.decode(s2).longValue();
		mostSigBits <<= 16;
		mostSigBits |= Long.decode(s3).longValue();

		long leastSigBits = Long.decode(s4).longValue();
		leastSigBits <<= 48;
		leastSigBits |= Long.decode(s5).longValue();

		return new UUID(mostSigBits, leastSigBits);
	}

UUID.nameUUIDFromBytes(name)方法并非是把byte[]类型转换为UUID类型,这点需要新手注意。

实际的转换方法如下:

public static UUID fromByte(byte[] data) {
		if (data.length != 16) {
			throw new IllegalArgumentException("Invalid UUID byte[]");
		}

		long msb = 0;
		long lsb = 0;
		for (int i = 0; i < 8; i++)
			msb = (msb << 8) | (data[i] & 0xff);
		for (int i = 8; i < 16; i++)
			lsb = (lsb << 8) | (data[i] & 0xff);

		return new UUID(msb, lsb);
	}

UUID转换为byte[]的方法

	public static byte[] toByte(UUID uuid) {
		ByteArrayOutputStream ba = new ByteArrayOutputStream(16);
		DataOutputStream da = new DataOutputStream(ba);
		try {
			da.writeLong(uuid.getMostSignificantBits());
			da.writeLong(uuid.getLeastSignificantBits());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ba.toByteArray();
	}


你可能感兴趣的:(java)