David Foie Gras
David Foie Gras

Reputation: 2080

How to get specific value from this function?

I read this : https://stackoverflow.com/a/37605582/6426449

START_TIME = a constant that represents a unix timestamp

def make_id():

    t = int(time.time()*1000) - START_TIME
    u = random.SystemRandom().getrandbits(23)
    id = (t << 23 ) | u

    return id

def reverse_id(id):
    t  = id >> 23
    return t + START_TIME 

From above def, How to get t and u of id(It's generated from def make_id)?

Like

def get_t(id):
    some methods
    return t

def get_u(id):
    some methods
    return u

Upvotes: 0

Views: 65

Answers (1)

Barmar
Barmar

Reputation: 781210

To get t, just undo the left shift with a right shift.

def get_t(id):
    return id >> 23

To get u, use a bit mask with the rightmost 23 bits set

def get_u(id):
    return id & 0x7fffff

Upvotes: 1

Related Questions