base2(3f) - [M_strings:BASE] convert whole number to string in base 2
(LICENSE:PD)
function base2(int)
integer,intent(in) :: int
character(len=:),allocatable :: base2
Convert a whole number to a string in base 2.
This is often done with the B edit descriptor and
an internal WRITE() statement, but is done without
calling the I/O routines, and as a function.
int input string representing numeric whole value
base2 string representing input value in base 2
Sample program:
program demo_base2
use M_strings, only : base2
implicit none
write(*,'(a)') base2(huge(0))
write(*,'(a)') base2(0)
write(*,'(a)') base2(64)
write(*,'(a)') base2(-64)
write(*,'(a)') base2(-huge(0)-1)
end program demo_base2
Results:
> 1111111111111111111111111111111
> 0
> 1000000
> 11111111111111111111111111000000
> 10000000000000000000000000000000
John S. Urban
Public Domain
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer, | intent(in) | :: | x |
function base2(x) result(str)
! return string representing number as a binary number. Fixed-length string:
integer, intent(in) :: x
integer :: i
character(len=max(1,bit_size(x)-leadz(x))) :: str
associate(n => len(str))
str = repeat('0',n)
do i = 0,n-1
if (btest(x,i)) str(n-i:n-i) = '1'
end do
end associate
end function base2