I have two binary integers, x0
and x1
that are 8 bits (so they span from 0 to 255). This statement is always true about these numbers: x0 & x1 == 0
. Here is an example:
bx0 = 100 # represented as 01100100 in binary
bx1 = 129 # represented as 10000001 in binary
So I need to do the following operation on these numbers. First, interpret these binary representations as ternary (base-3) numbers, as follows:
tx0 = ternary(bx0) # becomes 981 represented as 01100100 in ternary
tx1 = ternary(bx1) # becomes 2188 represented as 10000001 in ternary
Then, swap all of the 1
in the ternary representation of tx1
to 2
:
tx1_swap = swap(tx1) # becomes 4376, represented as 20000002 in ternary
Then use a ternary version of OR
on them to get the final combined number:
result = ternary_or(tx0, tx1_swap) # becomes 5357, represented as 21100102 in ternary
I don't need the ternary representation saved at any point, I only need the result, where for example result=5357
. Of course I could code this by converting the numbers to binary, converting to ternary, etc.. but I need this operation to be fast because I am doing this many times in my code. What would a fast way to implement this in python?
swap
is just multiplying by two andternary_or
is just addition... oops – Everetteevergladeternary
because a list of 255 integers shouldn't be large in memory... and the other two operations are just multiplication by two and addition. Thanks for the comments, I want to give someone credit so if anyone wants to write-up that solution I'll give them the green check mark. If not I'll write it up myself. – Everetteevergladeint(format(bx0, "b"), base=3) + 2 * int(format(bx1, "b"), base=3)
achieve what you ask for? – Reminisce