Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to generate 64 bits long int to serve as unique ID's for documents.

One idea is to combine the user's ID, which is a 32 bit int, with the Unix timestamp, which is another 32 bits int, to form an unique 64 bits long integer.

A scaled-down example would be:

Combine two 4-bit numbers 0010 and 0101 to form the 8-bit number 00100101.

  1. Does this scheme make sense?
  2. If it does, how do I do the "concatenation" of numbers in Python?
like image 276
Continuation Avatar asked Aug 24 '10 03:08

Continuation


4 Answers

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
>>>
like image 186
sykora Avatar answered Nov 16 '22 02:11

sykora


foo = <some int>
bar = <some int>

foobar = (foo << 32) + bar
like image 44
Amber Avatar answered Nov 16 '22 02:11

Amber


This should do it:

(x << 32) + y
like image 27
carl Avatar answered Nov 16 '22 02:11

carl


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'
like image 36
Brian Larsen Avatar answered Nov 16 '22 01:11

Brian Larsen