Community
cancel
Showing results for
Did you mean:
Highlighted
New Contributor II
113 Views

BINARY NUMBER and the DIGITS

If I have a binary number 101010 - as a decimal number 42 - is there an easy FORTRAN function to convert to a binary number and then determine the order of 1 and 0's --

John

Tags (1)
5 Replies
Highlighted
Valued Contributor II
113 Views

John

I'm not sure exactly what you mean. All numbers are stored internally as binary. You can use internal write to put the binary format of a number into a character string which you can print or process somehow.

If you want to test whether a particular bit is set or not you should look up BTEST in the help. The help also points to functions that allow the user to clear, set, or swap a particular bit.

Les

Highlighted
Valued Contributor III
113 Views

for example

```integer(4)      :: l1
character(32) :: gchar
write(gchar,'(B32.32)') l1```

which would set the string to '00000000000000000000000000010001' if L1 was 17

Highlighted
Employee
113 Views

There's also the intrinsic function POPCNT which will tell you the number of 1 bits in a value. (see also LEADZ and TRAILZ.)

Highlighted
New Contributor II
113 Views
```program Console1

implicit none
character(6) :: gchar
character :: a
integer :: i = 2
integer :: pos
logical :: bool

integer(4)      :: l1
l1 = 17
write(gchar,'(B6.6)') l1

do pos=6,0,-1
bool = btest(i, pos)
if(bool .eq. .TRUE.) then
print *, pos, 1
else
print *, pos, 0
endif
end do

end program Console1
```

Explanation:

In structures a restraint point can have 6 degrees of - each freedom is either set or released ie 1 or 0 is the usual code.  One ends up with a file with every joint having 6 integers usually stored as integer a(6) - one ends up trying to remember binary codes.  Now AUTODESK has a neat function in AutoCAD for setting some switches - you pick a decimal - 1, 2, 4, 8 and it sets the switch - I was wondering as I developed Borr - see the long discussion top that now runs to 30 pages if printed - I did - if I could use a integer code 0- 63 to cover all the restraint options.  The answer is a resounding yes, but one needs a large case statement to step through the combinations - or look up the binary equivalent of the integer directly.  So now I can input a full restraint as a 63 and a free as 0, lot less typing and less likely to miss one.  The other common one is 111000 or 56.  I was not aware of the BTEST function and my INTEL install on the home computer does not give me a nice help system - a WINDOWS 10 upgrade appears to have played with it - no search no nothing,  so I asked.

This code is great - thanks

John

Highlighted
Black Belt
113 Views

By the use of a binary bit field, you imply that multiple bits can be set. Therefor you would not have a select case, but rather you would have a filter.