Horizon
Member in Training
Posts: 32
|
Post by Horizon on Mar 27, 2020 11:54:11 GMT
Hello, I'd like to ask for some advice on converting binary to decimal, I've looked at a simple method of using a case function, but in this instance I need to work with numbers from 0 to 1025 so that approach would be somewhat impractical. My thoughts are floating around using a string variable say bin$ and using Len to determine its length and in turn recognising each 0 or 1 by its position to calculate the decimal value. 'Where a binary string does not exceed 10 bits
n = 0
bin$="1101001001" 'in this example we arrive at the decimal value of 814
for i = 1 to Len(bin$)
a$ = mid$(bin$, i, 1)
next i
if mid$(bin$, 10, 1)= "0" then n=n+0 else n=n+1
if mid$(bin$, 9, 1) = "0" then n=n+0 else n=n+2
if mid$(bin$, 8, 1) = "0" then n=n+0 else n=n+4
if mid$(bin$, 7, 1) = "0" then n=n+0 else n=n+8
if mid$(bin$, 6, 1) = "0" then n=n+0 else n=n+16
if mid$(bin$, 5, 1) = "0" then n=n+0 else n=n+32
if mid$(bin$, 4, 1) = "0" then n=n+0 else n=n+64
if mid$(bin$, 3, 1) = "0" then n=n+0 else n=n+128
if mid$(bin$, 2, 1) = "0" then n=n+0 else n=n+256
if mid$(bin$, 1, 1) = "0" then n=n+0 else n=n+512
print n
There's probably a better approach than this, but as I'm dealing with fixed lengths of Binary . Would there be a more efficient approach?
|
|
|
Post by tsh73 on Mar 27, 2020 12:50:26 GMT
You surely mean 841?
bin$="1101001001" 'in this example we arrive at the decimal value of 814 !! actually 841
n = 0 for i = 1 to Len(bin$) a$ = mid$(bin$, i, 1) n = n*2 if a$="1" then n =n+1 next print n
or even shorter
n = 0 for i = 1 to Len(bin$) n = n*2 + val(mid$(bin$, i, 1)) next print n
|
|
Horizon
Member in Training
Posts: 32
|
Post by Horizon on Mar 27, 2020 22:59:28 GMT
Thanks tsh73,
Its a great solution.
|
|
|
Post by zzz000abc on Mar 28, 2020 17:02:47 GMT
nice solution by tsh. here is my version :
d=0 input "enter any number in bin form ";bin$ l=len(bin$) for i=1 to l d=val(mid$(bin$,l-i+1,1))*2^(i-1)+d next print d
i think we can write a recursive function also
|
|