Skip to content Skip to sidebar Skip to footer

How To Merge Two Binary Numbers Into A Ternary Number

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 =

Solution 1:

The fastest way to do this is probably with decimal addition:

a = 1100100b = 10000001result = int(str(a+2*b),3) #5357

You won't find ternary-wise operators in python (or any other language that I know of.) Since you need to go above bitwise operations, your next-fastest option is integer addition, which every computer on Earth is optimized to complete.

Other solutions that convert to ternary to get this done will require you to cast back and forth to strings which takes much longer than decimal addition. This only requires one string cast at the end, assuming you even need the decimal version of the final ternary number.

Solution 2:

Re-explanation for dummies like me:

A straightforward way to "encode" two binary mutually exclusive numbers (w & b == 0) in ternary would be:

white_black_empty = lambda w, b: int(format(b, 'b'), base=3) + \
                                 int(format(w, 'b').replace('1','2'), base=3)

Here are all possible 2-bit variants:

white_black_empty(0b00, 0b00) == 0
white_black_empty(0b00, 0b01) == 1
white_black_empty(0b01, 0b00) == 2
white_black_empty(0b00, 0b10) == 3
white_black_empty(0b00, 0b11) == 4
white_black_empty(0b01, 0b10) == 5
white_black_empty(0b10, 0b00) == 6
white_black_empty(0b10, 0b01) == 7
white_black_empty(0b11, 0b00) == 8

By observing that int(format(w, 'b').replace('1','2'), base=3) is actually equal to double of int(format(w, 'b'), base=3) (for example, 20220023 == 10110013*2), we get the solution that @Mark Dickinson posted in the comments above:

white_black_empty = lambda w, b: int(format(b, 'b'), base=3) + \
                                 int(format(w, 'b'), base=3)*2

Post a Comment for "How To Merge Two Binary Numbers Into A Ternary Number"