我有以下程序给出一个最小的示例,我对通用或Fortran中的位表示都不了解。如果我用编译,gfortran 7.5
或者ifort 18.0
它通过了所有断言,而我不明白为什么。
函数popcnt返回I的二进制表示形式中设置的位数(“ 1”位)。
以我的理解,有符号整数的符号被编码为一位,因此,如果我从popcnt(n)
转到popcnt(-n)
它,则应改变一位。如果我可以表示n
为2的幂,则它应该具有popcnt
1或2 的幂(取决于符号)。我的思维错误是什么?
program bit_sizes
use iso_fortran_env, only: int64
implicit none
integer(int64), parameter :: n = -4294967296_int64
call assert(2_int64 ** 32_int64 == -n)
call assert(popcnt(-n) == 1)
call assert(popcnt(n) == 32)
contains
subroutine assert(cond)
logical, intent(in) :: cond
if (.not. cond) error stop
end subroutine
end program
错误是假定处理器将遵循该逻辑:-)
正整数遵循简单的级数,负整数不保证其表示形式。
我编写了一个例程来显示Fortran值中的位串,该例程将用户从命令行输入。检查您的结果:
program bit_sizes
use iso_fortran_env, only: int64
implicit none
integer(int64) :: n
do while (.true.)
write(*,*) 'enter value'
read(*,*) n
write(*,*) 'n', n
write(*,*) 'popcnt(n)', popcnt(n)
call print_bitstring(n)
write(*,*) '-n', -n
write(*,*) 'popcnt(-n)', popcnt(-n)
call print_bitstring(-n)
end do
contains
subroutine assert(cond)
logical, intent(in) :: cond
if (.not. cond) error stop
end subroutine assert
subroutine print_bitstring(i)
integer(kind=int64), intent(in) :: i
integer :: j, n
character(len=:), allocatable :: bitstring
n = bit_size(i)
allocate(character(len=n) :: bitstring)
do j = 1, n
if (btest(i,j-1)) then
bitstring(j:j) = '1'
else
bitstring(j:j) = '0'
end if
end do
write(*,*) bitstring
end subroutine print_bitstring
end program bit_sizes
在Linux 64位上使用gfortran,我有
$ ./bit_sizes
enter value
1
n 1
popcnt(n) 1
1000000000000000000000000000000000000000000000000000000000000000
-n -1
popcnt(-n) 64
1111111111111111111111111111111111111111111111111111111111111111
enter value
2
n 2
popcnt(n) 1
0100000000000000000000000000000000000000000000000000000000000000
-n -2
popcnt(-n) 63
0111111111111111111111111111111111111111111111111111111111111111
enter value
4294967296
n 4294967296
popcnt(n) 1
0000000000000000000000000000000010000000000000000000000000000000
-n -4294967296
popcnt(-n) 32
0000000000000000000000000000000011111111111111111111111111111111
enter value