0
How this code works?
ComputerUnitsToByte = lambda c, u: `c << " KB MB G TB P".find(u)`
2 Answers
+ 1
first, there is no need for ` symbols in lambda function, you will have an error.
so, how it works:
string.find(substring) returns an index of first found substring in string.
"python".find("p") == 0
"monty".find("y") == 4
a string with spaces and unit names is built such way that .find returns 10 for KB, 20 for MB and so on
that is made because 1 KB == 1024 B, and 1024 is 2**10. so there is 2**10 bytes in kilobyte, 2**20 in megabyte
<< is a left bit shifting operator. it shifts binary representation of number (c in you code) by specified amount of bits to the left, adding zeros at the end.
in binary math shifting by 1 bit to the left is equal to multiplication by 2. (in decimal - by 10, you can see it just writing another zero after a number)
2 << 4 == 32, equals to:
0b00000010 << 4 == 0b00100000
so, this function takes as arguments a number and a string with specified unit, finds position of this unit in large string (it would be 10, 20, 30...) and then shifts given number to the found amount of bits, thus multiplicating a number by 2**amount
0
thanks!! very informative answer