Created
February 16, 2021 09:43
-
-
Save ivan-pi/384003e9291b9363d6a2415c50bed056 to your computer and use it in GitHub Desktop.
Check processor endianess in Fortran
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!> Check Endianess | |
!> | |
!> Inspect the endianess of the platform. | |
!> | |
!> Based on a program posted by @urbanjost (urbanjost@comcast.net) | |
!> posted at https://github.com/fortran-lang/stdlib/issues/323. The original | |
!> program was based on ideas from the Code Tuning co-guide, 1998 Lahey Fortran | |
!> Users' Conference. | |
!> | |
!> Author: Ivan Pribec (ivan.pribec@gmail.com) | |
!> Date: Feb 16, 2021 | |
!> | |
program chkend | |
use, intrinsic :: iso_fortran_env, only: int32 | |
! Fill each byte of the `i` with the ascii characters | |
! of the numerals 0, 1, 2, and 3. | |
integer(int32), parameter :: i = shiftl(iachar('0'), 0) + & | |
shiftl(iachar('1'), 8) + & | |
shiftl(iachar('2'), 16) + & | |
shiftl(iachar('3'), 24) | |
! The value of `i` is 858927408 | |
! Transfer the bit representation of `i` to a character sequence. | |
character(len=4), parameter :: c = transfer(i,'0123') | |
! Use a derived type to mimic an enumerator | |
type :: endianness_type | |
integer :: little = 1, big = 2, mixed1 = 3, mixed2 = 4 | |
integer :: native = findloc(c == ['0123','3210','1032','2301'],.true.,1) | |
end type | |
type(endianness_type), parameter :: endianess = endianness_type() | |
! Store a constant character expression of the endianess | |
! This could be extended to cover also the mixed endianess cases | |
character(len=*), parameter :: str_endianess = trim( & | |
merge("Little",merge("Big ","Mixed ",c=='3210'),c=='0123')) | |
! Use the endianess singleton | |
if (endianess%native == endianess%little) then | |
write(*,*) 'Machine is Little-Endian ' | |
else if(endianess%native == endianess%big) then | |
write(*,*) 'Machine is Big-Endian ' | |
else | |
write(*,*) 'Mixed endianity machine ... ' | |
end if | |
! Use the string representation | |
write(*,*) "Machine is "//str_endianess//"-Endian" | |
end program |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment