Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Fortran

Idiom #251 Parse binary digits

Extract integer value i from its binary string representation s (in radix 2)
E.g. "1101" -> 13

character (len=:), allocatable :: s
integer :: i  
s = '1101'
read (s,'(B4)') i

  

The B4 format means a string of length 4. The length of the field could be adjusted by constructing the format field on the fly with an internal write.
(def i (read-string (str "2r" s)))

New implementation...