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
//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
Hi.
Try this:
set RNumber="100"
set RowResult=0,Power=1
for i=$LENGTH(RNumber):-1:1 {
set RowResult = RowResult + ($EXTRACT(RNumber,i)* Power)
set Power = Power * 2
}
Regards,
Matjaž
Thank you very much. I have just used it in my methods and it works. Your assistance is very much appreciated !
Or this
BinaryToDecimal(Binary,Debug=0)
i Debug {
w !,"Binary number: ",Binary
w !,"Bit",?20,"Cumulative",!
}
s Decimal=0
f Power=0:1 {
s Bit=$e(Binary,*) ; last digit
q:Bit="" ; at end
s $e(Binary,*)="" ; shorten binary number by removing last character
s Integer=(2**Power)*Bit ; 2**0 =1, 2**1 =2, 2**2 =4 etc..
s Decimal=Decimal+Integer ; running decimal sum of each Bit
i Debug w Integer,?20,Decimal,!
}
q Decimal
Thanks
For such a task, the Horner's method was introduced. Fast and simple.
Hardcore ObjectScript programer place those few commands into one line
and doesn't care about errors ;-))
Thanks
Social networks
InterSystems resources
Log in or sign up
Log in or create a new account to continue
Log in or sign up
Log in or create a new account to continue
Log in or sign up
Log in or create a new account to continue