Reputation: 1165
Can someone please help me out in forming an easy function to extract the leastSignificant & mostSignificant bits in Python?
Ex code in Java:
UUID u = UUID.fromString('a316b044-0157-1000-efe6-40fc5d2f0036');
long leastSignificantBits = u.getLeastSignificantBits();
private UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
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);
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
--> Output value: -1160168401362026442
Upvotes: 3
Views: 2182
Reputation: 1
FYI- In the case that you want to convert from Sigbits to UUID.
def sigbit2uuid(msb,lsb):
x = msb
if x <= 0x7FFFFFFFFFFFFFFF:
x += 0x10000000000000000
msb_s=format(x,'x')
msb_sl=[msb_s[:8],msb_s[8:12],msb_s[-4:]]
msb_r='-'.join(msb_sl)
y = lsb
if y <= 0x7FFFFFFFFFFFFFFF:
y += 0x10000000000000000
lsb_s=format(y,'x')
lsb_sl=[lsb_s[:4],lsb_s[-12:]]
lsb_r='-'.join(lsb_sl)
uuid=msb_r+'-'+lsb_r
return uuid
Upvotes: 0
Reputation: 140168
efe640fc5d2f0036
in decimal is 17286575672347525174. Subtract 0x10000000000000000
from it & negate: you get -1160168401362026442
int("efe640fc5d2f0036",16)-0x10000000000000000 -> -1160168401362026442
Note that it's only guesswork but seems to work with the sole test case you provided (fortunately it was negative). Call that reverse engineering.
Take 2 last hex values (dash separated) and join them. I suppose the storage means that it becomes negative when first digit is above 7, so negate it with higher 2-power if that's the case:
def getLeastSignificantBits(s):
hv = "".join(s.split("-")[-2:])
v = int(hv,16)
if int(hv[0],16)>7:
# negative
v = v-0x10000000000000000
return v
print(getLeastSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036'))
result:
-1160168401362026442
Providing a method which takes the whole string and returns lsb & msb couple
def getLeastMostSignificantBits(s):
sp=s.split("-")
lsb_s = "".join(sp[-2:])
lsb = int(lsb_s,16)
if int(lsb_s[0],16)>7:
# negative
lsb = lsb-0x10000000000000000
msb_s = "".join(sp[:3])
msb = int(msb_s,16)
if int(msb_s[0],16)>7:
# negative
msb = msb-0x10000000000000000
return lsb,msb
print(getLeastMostSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036'))
result:
(-1160168401362026442, -6694969989912915968)
Upvotes: 3
Reputation: 3757
Old post but still... Just thought I'd add this:
import struct
import uuid
u = uuid.UUID('c88524da-d88f-11e9-9185-f85971a9ba7d')
msb, lsb = struct.unpack(">qq", u.bytes)
This give the values:
(-3997748571866721815, -7960683703264757123)
... and if I input those into the java.util.UUID constructor, it gives me back the uuid "c88524da-d88f-11e9-9185-f85971a9ba7d"
Upvotes: 6