Hi everyone, this is my first post and it just happened to come across this problem while I was registering for your forum. So nice to meet you
The problem itself is pretty straightforward. For simplicity I would describe it using C, but I think it is so simple so anybody can implement its solution in every (general purpose) language.
If I had to give a name to the problem, I would name it convert an integer to its symmetrical binary representation.
Going a bit further, suppose we have an
int variable with value of
255, in binary this is
0000 0000 0000 0000 0000 0000 1111 1111 in a machine where
int size is four bytes. Now suppose LSB (less significant bit) is placed at index 0, second LSB is placed at index 1 etc. So MSB (most significant bit) is placed at index 31 in that case. What we want, is exchange positions of
31-i bits in that case, where
i can take values from [0,31]
It is straightforward output should be
1111 1111 0000 0000 0000 0000 0000 0000.
We need to create a function that takes an at least an int as an argument (but this is not a restriction) and returns its binary symmetrical, as described above. Using only binary operators. Ok, if this makes it difficult for you can have a try without this restriction.
(on a 4-byte
##Going a bit further
Try making it work for 33 bits (32-bits + a bit further = 33-bits ). I’m joking.
Try accepting as input not only
int types all the numerical types like
doubles etc. So the challenge would be to find a more generic solution, that doesn’t depend on the size of the data. In this case I think data size should be provides as input to the function.
#####EDIT: Made some changes to the numbers and the inputs/outputs because I used 16-bits instead of 32.