关于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();
	}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值