【问题标题】:How to get specific value from this function?如何从此函数中获取特定值?
【发布时间】:2018-03-07 08:37:04
【问题描述】:

我读到这个: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 

从上面的def,如何得到idtu(由def make_id生成)?

喜欢

def get_t(id):
    some methods
    return t

def get_u(id):
    some methods
    return u

【问题讨论】:

  • 你不能。为什么要这样做?
  • @DanielRoseman 为什么你不能?它是通过移位和 ORing 创建的,您可以通过移位和屏蔽来撤消它。
  • 好吧,显然你可以编写一个函数来做与那些相反的事情,但 OP 似乎想要访问现有函数中的实际变量。
  • @DanielRoseman 你在哪里看到的?问题是他想从id的值中获取它们。

标签: python


【解决方案1】:

要获得t,只需用右移撤消左移即可。

def get_t(id):
    return id >> 23

要获取u,请使用设置了最右边 23 位的位掩码

def get_u(id):
    return id & 0x7fffff

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2015-07-13
    • 2019-11-22
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    相关资源
    最近更新 更多