Given an integer value, I need some way to find out the minimum number of bytes needed to store the value. The value may be signed or unsigned, up to 64-bit. Also take the sign bit into account for signed integers.
For example:
8 requires 1 byte at minimum
unsigned 255 requires 1 byte at minimum
signed 255 requires 2 bytes at minimum
4351 requires 2 bytes at minimum
-4294967296 requires 5 bytes at minimum
unsigned 0xFFFFFFFFFFFFFFFF requires 8 bytes at minimum
I can think of a quick-and-dirty way to solve this, using many if-statements, but there might be better (e.g. simpler, cleverer, faster) ways to do this. You may either assume a method with signature int (long value, bool signed) or two methods int (long value) (for signed) and int (ulong value) (for unsigned).
Let me give it a go at my own question. As far as I can tell, this is a correct solution, but it may not be optimal in speed, conciseness: