Module for dealing with unsigned integers in standard Fortran

Not an answer to your question, but I have read some materials saying that in most circumstances unsigned integers are best to be avoided in C++:

The bottom line of one of those articles is:

Avoid using unsigned ints in C and C++ unless you’re dealing with raw memory contents or performing bit manipulations like shifting or masking.

Now to Fortran, in case you need to fill an integer with a binary pattern you can use boz constants. More about them in the great blog post by @sblionel: Doctor Fortran in "We're All BOZos on This Bus" - Doctor Fortran

As an example you could do:

use iso_fortran_env, only: int8
integer(int8) :: a, b

a = int(128,int8)  ! requires -fno-range-check
! or
a = 128_int8       ! requires -fno-range-check
! or
b = int(b'10000000',int8)

print *, a, b
end

With recent gfortran versions you might need to use the flag -fno-range-check:

Disable range checking of input values during integer READ operations. For example, GNU Fortran will give an error if an input value is outside of the relevant range of [ -HUGE() : HUGE() ]. In other words, with INTEGER (kind=4) :: i , attempting to read -2147483648 will give an error unless -fno-range-check is given.

6 Likes