# Determine minimum integer storage type

**URL:** <https://discourse.julialang.org/t/determine-minimum-integer-storage-type/88001>\
**Category:** New to Julia\
**Tags:** question, type\
**Created:** [September 29, 2022, 5:57pm UTC](https://discourse.julialang.org/t/determine-minimum-integer-storage-type/88001 "2022-09-29T17:57:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![james3](https://avatars.discourse-cdn.com/v4/letter/j/b5e925/32.png) [@james3](https://discourse.julialang.org/u/james3)\
**Post date:** [September 29, 2022, 5:57pm UTC](https://discourse.julialang.org/t/determine-minimum-integer-storage-type/88001/1 "2022-09-29T17:57:52Z")

</div>

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

```julia
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?

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [September 29, 2022, 6:05pm UTC](https://discourse.julialang.org/t/determine-minimum-integer-storage-type/88001/2 "2022-09-29T18:05:12Z")

</div>

```julia
julia> findfirst(x->typemax(x)>=200, (UInt8, UInt16, UInt32, UInt64))
1

julia> findfirst(x->typemax(x)>=300, (UInt8, UInt16, UInt32, UInt64))
2

```

---

<div class="post-metadata">

**Author:** ![Palli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/palli/32/3380_2.png) [@Palli](https://discourse.julialang.org/u/Palli)\
**Post date:** [September 29, 2022, 6:08pm UTC](https://discourse.julialang.org/t/determine-minimum-integer-storage-type/88001/3 "2022-09-29T18:08:04Z")

</div>

You need that many bits:

```julia
julia> round(Int, log2(200), RoundUp) #bits
8

```

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
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):

```julia
julia> 2^20
1048576

```
