Concatenate two 32 bit int to get a 64 bit long in Python

耗尽温柔 提交于 2019-12-05 06:25:55
sykora

Left shift the first number by the number of bits in the second number, then add (or bitwise OR - replace + with | in the following examples) the second number.

result = (user_id << 32) + timestamp

With respect to your scaled-down example,

>>> x = 0b0010
>>> y = 0b0101
>>> (x << 4) + y
37
>>> 0b00100101
37
>>>
foo = <some int>
bar = <some int>

foobar = (foo << 32) + bar

This should do it:

(x << 32) + y

For the next guy (which was me in this case was me). Here is one way to do it in general (for the scaled down example):

def combineBytes(*args):
    """
    given the bytes of a multi byte number combine into one
    pass them in least to most significant 
    """
    ans = 0
    for i, val in enumerate(args):
        ans += (val << i*4)
    return ans

for other sizes change the 4 to a 32 or whatever.

>>> bin(combineBytes(0b0101, 0b0010))
'0b100101'

None of the answers before this cover both merging and splitting the numbers. Splitting can be as much a necessity as merging.

NUM_BITS_PER_INT = 4  # Replace with 32, 48, 64, etc. as needed.
MAXINT = (1 << NUM_BITS_PER_INT) - 1

def merge(a, b):
    c = (a << NUM_BITS_PER_INT) | b
    return c

def split(c):
    a = (c >> NUM_BITS_PER_INT) & MAXINT
    b = c & MAXINT
    return a, b

# Test
EXPECTED_MAX_NUM_BITS = NUM_BITS_PER_INT * 2
for a in range(MAXINT + 1):
    for b in range(MAXINT + 1):
        c = merge(a, b)
        assert c.bit_length() <= EXPECTED_MAX_NUM_BITS
        assert (a, b) == split(c)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!