+ 2

Output of 5 << 2

What means 5 << 2 and why it's 20. It was a task in a challenge I've faired.

21st Aug 2017, 12:21 PM
Stransparency
4 ответов
+ 3
5 in binary is 101(4 + 1). If you shift the bits to the left two times you get 10100, which is 16 + 4 = 20.
21st Aug 2017, 1:02 PM
Bebida Roja
Bebida Roja - avatar
+ 2
Knowing conversions between different bases will help you when manipulating the bits in numbers. This is used a lot in compression/encryption where bit manipulation is almost a "default". This is also used to configure options. Suppose you have a function which makes salad and takes one 4 bit number as argument(this number represents the ingredients). The first digit can be a boolean telling if there is lettuce, the second if there is tomatoes, the third one corn and the fourth one vinegar. makeSalad(14) would make the salad with tomatoes, corn and vinegar, but no lettuce, because 14 is 1110 in binary. Suppose you now finish all the tomatoes you have. Then all the numbers you enter to that function cannot have the tomatoes bit set, so you need to make a mask. noTomatoesMask = 1101 Then you need to AND together the ingerdients you want and the ones you dont have, so 14 & noTomatoesMask -> 1100 (12 in decimal) This can be generalized like so (in C++): #define lettuce 1 #define tomatoes 2 #define corn 4 #define vinegar 8 #define noLettuceMask ~lettuce #define noTomatoesMask ~tomatoes ... Then you call the function using makeSalad((tomatoes | lettuce | vinegar) & noLettuceMask) which is same as makeSalad(11 & 14) which is indeed the same as makeSalad(10) This will make the salad with tomatoes and vinegar, as there is no lettuce left. I hope this analogy helps understanding the importance of bit manipulation.
21st Aug 2017, 1:36 PM
Bebida Roja
Bebida Roja - avatar
0
Thanks for your answer. This means that I must learn the translation of binary code of the digits 0-... (?) to be able to answer correctly questions like this? Isn't it a bit hard as a challenge question? Because I don't need it really to know as a python programmer or? What's your meaning in this point? Greetings
21st Aug 2017, 1:06 PM
Stransparency
0
Thank you for your detailed explanation. In every case it improve my comprehension of the use of binary manipulation. My be you can help me understanding althoug why 101 is the same like 4 + 1 and 10100 is 16+4. What I understand at the moment is why a 2 bits shift of 101 is 10100. But I don't understand the correct translation. Greetings
21st Aug 2017, 1:48 PM
Stransparency