Question
· Aug 5, 2021

Conversion of a variable from Binary in to Decimal

I have been working within Objectscript for a few months and I am seeking assistance today because all of the help files within the docs.intersystems.com domain are currently down and they wont be back up until next week. (I raised a special ticket for this) 

I have been trying to figure out how to  convert a binary number 0101001 in to a decimal number using a variable called CNumber and I have tried using the method below and it hasnt worked. I think it may be due to the fact that this assumes an array or some sort. I tried using online hexadecimal calculators and the resulting output is incorrect.

If RNumber is 100 

//for i=$LENGTH(RNumber):-1:1 {
        //set RowResult = RowResult + ( $EXTRACT(RNumber(i))* Power )
        //set Power = Power * 2
  // }

The RowResult = 512 

And as you can appreciate this isn't the number I am looking for.

Does anyone know of a reliable way of obtaining the Binary to Decimal result that I desire ?

Thanks in advance

Product version: IRIS 2021.1
$ZV: 1.1
Discussion (6)0
Log in or sign up to continue

Or this

BinaryToDecimal(Binary,Debug=0)
              Debug {
                             !,"Binary number: ",Binary
                             !,"Bit",?20,"Cumulative",!
              }
              Decimal=0
              Power=0:1 {
                             Bit=$e(Binary,*) ; last digit
                             q:Bit=""  ; at end
                             s $e(Binary,*)="" ; shorten binary number by removing last character
                             Integer=(2**Power)*Bit ; 2**0 =1, 2**1 =2, 2**2 =4 etc..
                             Decimal=Decimal+Integer ; running decimal sum of each Bit
                             Debug Integer,?20,Decimal,!
              }
              Decimal

For such a task, the Horner's method was introduced. Fast and simple.

ClassMethod BinToDec(bin)
{
   if $translate(bin,10)="" { // formal check, bin should only contain '1' and '0'
      set res=0
      for i=1:1:$length(bin) set res=res*2+$extract(bin,i)
      quit res
   } else { ztrap "NBIN" }
}


Hardcore ObjectScript programer place those few commands into one line

bin2dec(bin) { s res=0 f i=1:1:$l(bin) { s res=res*2+$e(bin,i) } q res }


and doesn't care about errors ;-))