base2 Function

public function base2(x) result(str)

NAME

base2(3f) - [M_strings:BASE] convert whole number to string in base 2
(LICENSE:PD)

SYNOPSIS

function base2(int)

 integer,intent(in)           :: int
 character(len=:),allocatable :: base2

DESCRIPTION

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.

OPTIONS

int   input string representing numeric whole value

RETURNS

base2   string representing input value in base 2

EXAMPLE

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

AUTHOR

John S. Urban

LICENSE

Public Domain

Arguments

Type IntentOptional Attributes Name
integer, intent(in) :: x

Return Value character(len=max)


Contents

Source Code


Source Code

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