Reputation: 502
Problem Statement
I have two different patterns to represent whole numbers using binary digits as follows:
First (the standard decimal to binary conversion):
0 -> 000
1 -> 001
2 -> 010
3 -> 011
4 -> 100
5 -> 101
6 -> 110
7 -> 111
Second:
0 -> 0000
1 -> 0001
2 -> 0010
3 -> 0100
4 -> 1000
5 -> 0011
6 -> 0101
7 -> 1001
8 -> 0110
9 -> 1010
10 -> 1100
11 -> 0111
12 -> 1011
13 -> 1101
14 -> 1110
15 -> 1111
Explaination: First, take flip one bit each, highest priority to the least significant bit. Then in second iteration, keep first bit flipped and then flip the rest bits in order as before. In the third iteration, the least significant bit is unset, and then second significant bit set and then pattern continued.
But now, let's say I want to combine the first and second pattern into one single pattern where some parts are defined by the first patten while the others are defined by the second pattern. For example:
(First pattern, most 3 significant digits)(Second pattern, least 3 significant digits)
0 -> 000000
1 -> 000001
2 -> 000010
3 -> 000100
4 -> 000011
5 -> 000101
6 -> 000110
7 -> 000111
8 -> 001000
9 -> 001001
10 -> 001010
11 -> 001100
12 -> 001011
13 -> 001101
14 -> 001110
15 -> 001111
16 -> 010000
17 -> 010001
...
010111
011000
...
The goal:
Input which tells which group of bits have which of these 2 patterns (no. of bits can be as long as we want and the pattern repetition can keep shifting between groups of bits in this set infinitely); a whole number.
Output which converts the whole number to the corresponding binary representation based on the input pattern. E.g. 12 -> 001011
Where I am stuck:
The binary conversion is straight forward. The second pattern, I'm not really sure how to make. Even if I can convert the whole number to the second pattern binary representation, how could I combine the both types to find the correct binary equivalent for my input number? Since there is a pattern here, I'm sure there must be an elegant mathematical representation for this!
What is my use case?
I'm writing a code for an application where I want to create a search pattern similar to this binary representation, based on a similar type of input.
Upvotes: 0
Views: 148
Reputation: 682
Assuming you have calculated first pattern and second pattern for a number.
Convert them back to "normal" decimal and then left shift firstNumber by 3 firstPatterNo << 3
and then do OR of 2 numbers firstPatterNo | secondPatterNo
.
firstPatterNo = 3 // 011 (normal decimal representations)
secondPatternNo = 4 // 100 (normal decimal representations)
combined = (firstPatterNo << 3) | secondPatternNo
// Convert combined to normal binary representation
BTW whats the logic behind second pattern ? I am not able to figure out.
Upvotes: 0