# Get integer type of specified width

**URL:** <https://discourse.julialang.org/t/get-integer-type-of-specified-width/81900>\
**Category:** General Usage\
**Created:** [May 30, 2022, 6:06am UTC](https://discourse.julialang.org/t/get-integer-type-of-specified-width/81900 "2022-05-30T06:06:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)\
**Post date:** [May 30, 2022, 6:06am UTC](https://discourse.julialang.org/t/get-integer-type-of-specified-width/81900/1 "2022-05-30T06:06:39Z")

</div>

Is there a nicer way of implementing this? Perhaps without hardcoding UInts of specific sizes?

```julia
# Inverse sizeof, basically.
of_exact_size(::Val{1}) = UInt8
of_exact_size(::Val{2}) = UInt16
of_exact_size(::Val{4}) = UInt32
of_exact_size(::Val{8}) = UInt64
of_exact_size(::Val{16}) = UInt128

# Returns the smallest unsigned integer type not narrower than
# min_width.
#
# There's no dynamic dispatch according to JET.jl, at least with Julia
# 1.8.
of_size(::Val{min_width}) where {min_width} =
  of_exact_size(Val(nextpow(2, min_width)))

```

---

<div class="post-metadata">

**Author:** ![Jollywatt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jollywatt/32/202198_2.png) [@Jollywatt](https://discourse.julialang.org/u/Jollywatt)\
**Post date:** [May 30, 2022, 6:52am UTC](https://discourse.julialang.org/t/get-integer-type-of-specified-width/81900/2 "2022-05-30T06:52:46Z")

</div>

The built-in `sizeof` is handy. You might try…

```julia
function of_size(min_width)
	types = sort(subtypes(Unsigned), by=sizeof)
	for type in types
		sizeof(type) >= min_width && return type
	end
	nothing
end

```

…although it looks like you want to compute `of_size` it at compile time. If you’re doing code generation, I’d use a macro-approach, and use `of_size` as normal function. (I try to avoid `Val`.)
