POPCNT(3) - [BIT:COUNT] Number of bits set
result = popcnt(i)
elemental integer function popcnt(i)integer(kind=KIND), intent(in) :: i
o I may be an integer of any kind. o The return value is an integer of the default integer kind.
POPCNT(3) returns the number of bits set to one in the binary representation of an integer.
o I : value to count set bits in
The number of bits set to one in I.
Sample program:
program demo_popcnt use, intrinsic :: iso_fortran_env, only : integer_kinds, & & int8, int16, int32, int64 implicit none character(len=*),parameter :: pretty=(b64,1x,i0) ! basic usage print pretty, 127, popcnt(127) print pretty, int(b"01010"), popcnt(int(b"01010"))Results:! any kind of an integer can be used print pretty, huge(0_int8), popcnt(huge(0_int8)) print pretty, huge(0_int16), popcnt(huge(0_int16)) print pretty, huge(0_int32), popcnt(huge(0_int32)) print pretty, huge(0_int64), popcnt(huge(0_int64)) end program demo_popcnt
Note that on most machines the first bit is the sign bit, and a zero is used for positive values; but that this is system-dependent. These are typical values, where the huge(3) function has set all but the first bit to 1.
> 1111111 7 > 1010 2 > 1111111 7 > 111111111111111 15 > 1111111111111111111111111111111 31 > 111111111111111111111111111111111111111111111111111111111111111 63
Fortran 2008
There are many procedures that operator or query values at the bit level:
POPPAR(3), LEADZ(3), TRAILZ(3) ATOMIC_AND(3), ATOMIC_FETCH_AND(3), ATOMIC_FETCH_OR(3), ATOMIC_FETCH_XOR(3), ATOMIC_OR(3), ATOMIC_XOR(3), BGE(3), BGT(3), BIT_SIZE(3), BLE(3), BLT(3), BTEST(3), DSHIFTL(3), DSHIFTR(3), IALL(3), IAND(3), IANY(3), IBCLR(3), IBITS(3), IBSET(3), IEOR(3), IOR(3), IPARITY(3), ISHFTC(3), ISHFT(3), MASKL(3), MASKR(3), MERGE_BITS(3), MVBITS(3), NOT(3), SHIFTA(3), SHIFTL(3), SHIFTR(3), STORAGE_SIZE(3)
Fortran intrinsic descriptions (license: MIT) @urbanjost
Nemo Release 3.1 | popcnt (3fortran) | November 02, 2024 |