Fortran整数的位大小

Fortran整数的位大小,fortran,bit,Fortran,Bit,我有下面的程序给一个我不懂的小例子 关于一般的位表示或Fortran中的位表示。 如果我使用gfortran 7.5或ifort18.0编译,它会通过所有断言,我不明白为什么 该函数返回I的二进制表示形式中设置的位数('1'位) 在我的理解中,有符号整数的符号是以一位编码的,所以如果我从popcnt(n)到popcnt(-n)它应该改变一位。 如果我可以将n表示为2的幂,则其popcnt应为1或2(取决于符号) 我的思维错误是什么 program bit_sizes use iso_fo

我有下面的程序给一个我不懂的小例子 关于一般的位表示或Fortran中的位表示。 如果我使用
gfortran 7.5
ifort18.0
编译,它会通过所有断言,我不明白为什么

该函数返回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
使用64位linux上的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
看看哪个描述了位数据的模型。特别注意“负整数作为位序列的解释取决于处理器。”