!=============Main Program==============
program main
implicit none
character(8) :: hex1 !分配字符长度,不然到后面只识别一个字符
integer :: dec_number
integer,external :: hex_to_dec
write(*,*)'Please type a Hex number:'
read(*,*)hex1
dec_number=hex_to_dec(hex1)
write(*,"('The input HEX is:',a10,'The output DEC is :',i10)")hex1,dec_number
stop
end program main
!=============Sub Program==============
function hex_to_dec(x)
character(8) :: x
integer :: hex_to_dec,sum,Length,i
integer,allocatable :: m(:)
character,allocatable :: hex(:)
length=len_trim(x)
if(mod(length,2) /= 0)write(*,*)'Please type a correct Hex number:'
allocate(hex(length))
allocate(m(length))
do i=1,length !从字符转化为十进制数值(0-16)
hex(i)=x(i:i)
if(48 <= ichar(hex(i)) .and. ichar(hex(i))<=57)then !判断是否是数字字符串
m(i)=ichar(hex(i))-48
elseif(97 <= ichar(hex(i)) .and. ichar(hex(i))<=102)then !判断是否是字母(a-f & A-F)
m(i)=ichar(hex(i))-87
elseif(65 <= ichar(hex(i)) .and. ichar(hex(i))<=70)then
m(i)=ichar(hex(i))-55
end if
end do
sum=0
do i=length,1,-1
sum=sum+m(i)*16**(4-i) !将Hex转换为Dec
end do
hex_to_dec=sum
end function hex_to_dec
!=============End of Program=============
n | Is an unsigned, positive default integer literal constant (with no kind parameter) indicating the number of characters in string (including blanks and tabs). The range of n is 1 through 2147483647 (2**31-1) on Intel® 64 architecture; 1 through 32767 (2**15-1) on IA-32 architecture. Actual useful ranges may be constrained by record sizes (RECL) and the file system. |
string | Is a string of printable ASCII characters. |
!=============Main Program==============
program main
implicit none
character(8) :: hex1 !分配字符长度,不然到后面只识别一个字符
integer :: dec_number
integer,external :: hex_to_dec
write(*,*)'Please type a Hex number:'
read(*,*)hex1
dec_number=hex_to_dec(hex1)
write(*,"('The input HEX is:',a10,'The output DEC is :',i10)")hex1,dec_number
read( hex1 , '(Z8)' ) dec_number
write(*,"('The input HEX is:',a10,'The output DEC is :',i10)")hex1,dec_number
stop
end program main
!=============Sub Program==============
integer function hex_to_dec(x)
character(8) :: x
integer :: sum,Length,i , m
character :: hex
length=len_trim(x)
if(mod(length,2) /= 0)write(*,*)'Please type a correct Hex number:'
sum = 0
do i=1,length !从字符转化为十进制数值(0-16)
hex = x(i:i)
Select Case( hex )
Case ( '0':'9' )
m= ichar(hex) - ichar('0')
Case( 'A':'F' )
m=ichar(hex) - ichar('A') + 10
Case( 'a':'f' )
m=ichar(hex) - ichar('a') + 10
End Select
sum = sum + m*16**(4-i) !将Hex转换为Dec
end do
hex_to_dec=sum
end function hex_to_dec
!=============End of Program=============
fcode 发表于 2014-5-3 18:25
楼主很好学,乐于动脑筋,赞一个。
有两个问题与楼主分享。
vvt 发表于 2014-5-4 06:51
楼主的代码如果输入2位十六进制,结果与 read( hex1 , '(Z8)' ) dec_number 的不同哦。是不是顺序有问题? ...
欢迎光临 Fortran Coder (http://bbs.fcode.cn/) | Powered by Discuz! X3.2 |