Greg,
I'm sure you and Barry and some others can improve on this, but it has
worked for my purposes.
[937]:print bit2int
parm BITS="^"
if "!BITS"="^"
echo Bit String must be provided
return
endif
if NOT NUMERIC("!BITS")
echo Bit String must be numeric
return
endif
setvar bitlen;len("!BITS")
setvar i;1
while i <= bitlen
setvar ipos;str("!BITS",!i,1)
if pos("!ipos","23456789",1) > 0
echo Bit String must contain only 0's and 1's
return
endif
setvar i;i+1
endwhile
setvar ipos;!bitlen
setvar ival;0
while ipos > 0
setvar iposval;str("!BITS",!ipos,1)
setvar ibit;!bitlen-!ipos
setvar ival;ival+(!iposval*(2^!ibit))
# echo !ival
setvar ipos;ipos-1
endwhile
echo !BITS is the binary equivalent of !ival
return
[937]:xeq bit2int 1001101
1001101 is the binary equivalent of 77
----- Original Message -----
From: "Stigers, Greg [And]" <[log in to unmask]>
To: "'Barry Lake'" <[log in to unmask]>; "Russ Smith" <[log in to unmask]>
Sent: Friday, November 17, 2000 2:06 PM
Subject: RE: Bitmapping script
> I had wondered if there was a way to reduce the while content to a single
> line. I like moving the divide by 2 into the while condition! I wonder if
> there is a way to eliminate the initialization of your binval (the output)
> outside of the while loop? Except it has to exist before the first
iteration
> of the while, doesn't it, or the statement that prepends to it will fail,
> right? Six lines, that's pretty good. Barry, feel free to repost this, not
> that you need my permission (but, no, I won't feel one upped; I like
seeing
> better ways to do things - thus the disclaimer with my post).
>
> I guess one could worry this to death with validating input, or handling
any
> maximum input or minimum length output. All told, I think this does what
it
> needs to.
>
> Russ, I still want to see your command file going the other way.
>
> -----Original Message-----
> From: Barry Lake [mailto:[log in to unmask]]
> Sent: Friday, November 17, 2000 4:47 PM
> To: Stigers, Greg [And]; Russ Smith
> Subject: Re: Bitmapping script
>
>
> Hi guys,
>
> I can't resist tweaking in order to maximize efficiency and compactness in
> my scripts. Here's my revision, thanks in part to a small piece I lifted
> from Greg's submission:
>
> :print num2bin
> parm innum=0
>
> setvar tnum !innum
> setvar binval "![tnum mod 2]"
>
> while setvar(tnum,tnum/2) > 0
> setvar binval "![tnum mod 2]" + binval
> endwhile
>
> echo !binval
> :num2bin
> 0
> :num2bin 0
> 0
> :num2bin 7
> 111
> :num2bin 4909283
> 10010101110100011100011
> :num2bin 65535
> 1111111111111111
> :num2bin 33554432
> 10000000000000000000000000
> :
>
> Cheers,
>
> Barry.
>
>
|