The task is simple but every programmer has implemented it at least once. Stackoverflow has a lot of samples, but are they short enough to win?
You're a grumpy programmer who was given the task of implementing file size input for the users. Since users don't use bytes everyone will just enter "1M", "1K", "3G", "3.14M" - but you need bytes! So you write a program to do the conversion.
Then your manager hands you dozens of user reports with complaints about weird large numbers in file size input. It seems you'll need to code the reverse conversion too.
What do you need to do?
Here's the trick: you should implement two-way conversion in single piece of code. Two separate functions used as needed? Nah, that's too simple - let's make one, short one!
For the purposes of this challenge, "kilobyte" means 1024 bytes, "megabyte" means 1024*1024 = 1048576 bytes, and "gigabytle" means 1024*1024*1024 = 1073741824 bytes.
Input -> Output 5 -> 5 1023 -> 1023 1024 -> 1K 1K -> 1024 1.5K -> 1536 1536 -> 1.5K 1048576 -> 1M 1M -> 1048576
- Test value will not exceed 2*1024*1024*1024 or 2G
- The following postfixes are used by users: K for kilobytes, M for megabytes, G for gigabytes
- Code is not required to work with negative numbers
- Do not use any external libraries (e.g.
BCMathin PHP) besides bundled ones (e.g.
- Standard loopholes are disallowed
- Code should not produce anything on stderr
- Your program can take input and produce output using standard methods