diff --git a/example/bitsets/example_bitsets_bit_count.f90 b/example/bitsets/example_bitsets_bit_count.f90 index 1cbd15f1e..a6abaeb90 100644 --- a/example/bitsets/example_bitsets_bit_count.f90 +++ b/example/bitsets/example_bitsets_bit_count.f90 @@ -3,6 +3,9 @@ program example_bit_count character(*), parameter :: & bits_0 = '0000000000000000000' type(bitset_64) :: set0 + type(bitset_large) :: set1 + logical, allocatable :: logi(:) + call set0%from_string(bits_0) if (set0%bit_count() == 0) then write (*, *) "FROM_STRING interpreted "// & @@ -12,4 +15,11 @@ program example_bit_count if (set0%bit_count() == 1) then write (*, *) "BIT_COUNT interpreted SET0's value properly." end if + + allocate( logi(1000), source=.false.) + logi(1::7) = .true. + set1 = logi + if (set1%bit_count() == count(logi)) then + write (*, *) "BIT_COUNT interpreted SET1's value properly." + end if end program example_bit_count diff --git a/src/stdlib_bitsets_large.fypp b/src/stdlib_bitsets_large.fypp index fef726525..c3fa1db0a 100644 --- a/src/stdlib_bitsets_large.fypp +++ b/src/stdlib_bitsets_large.fypp @@ -144,19 +144,13 @@ contains integer(bits_kind) :: bit_count class(bitset_large), intent(in) :: self - integer(bits_kind) :: block_, pos + integer(bits_kind) :: nblocks, pos - bit_count = 0 - do block_ = 1_bits_kind, size(self % blocks, kind=bits_kind) - 1 - do pos = 0, block_size-1 - if ( btest( self % blocks(block_), pos ) ) & - bit_count = bit_count + 1 - end do - - end do + nblocks = size( self % blocks, kind=bits_kind ) + bit_count = sum( popcnt( self % blocks(1:nblocks-1) ) ) - do pos = 0_bits_kind, self % num_bits - (block_-1)*block_size - 1 - if ( btest( self % blocks(block_), pos ) ) bit_count = bit_count + 1 + do pos = 0_bits_kind, self % num_bits - (nblocks-1)*block_size - 1 + if ( btest( self % blocks(nblocks), pos ) ) bit_count = bit_count + 1 end do end function bit_count_large