Suppose I have something that can take integer values from 1 to N. I want to determine the minimum integer type that will allow me to store these values. That is, I want to do something like

const N = 200
const N_type = required_integer_type(N)

So, in the N = 200 case we would have N_type = UInt8. If we instead had N = 300, we would have N_type = UInt16. (This is assuming we use unsigned integers.) Is there an easy way to achieve this?

i.e. UInt8, if you need negative numbers too, then Int9 (a sign always adds one bit, so maybe you can get away with 127 max?), which isn’t available, then next one Int16. In practice this usually mean Int32 is the happy medium if you want to save space, or just go with the default Int64 (least likely to overflow, not a huge concern, mostly for power, for any of them).

julia> typemax(Int32)
2147483647

I’m mulling over making a 21 or 20-bit Int, as a better happy medium (strictly 3 such encoded into one Int64), since often a reasonable max. (my type would get you a Float64 for power, since I feel not doing that is a design flaw of Julia):