Binary to Decimal and Back

Posted by SquareWheel on July 25, 2008, 10:42 p.m.

I saw the hexidecimal blog and figured, hey, I might as well post the scripts I made. Very simply, you input a string, and it outputs your string converted. Yes, I've seen smaller scripts which do the same thing, but I thought it might be fun to make myself, and hey, it was.

Binary to Decimal

Quote:

//Setup Variables

var len,total,i,ii;

bin=string(argument0)

len=string_length(bin)

len=8-len

//Cleaning the String

bin=string_digits(bin)

for(i=0;i<len;i+=1)

bin="0"+bin

//Make the Conversion

total=0;

for(i=8;i>0;i-=1)

{

ii=0

ii=real(string_char_at(bin,i))

ii=ii*power(2,8-i)

total+=ii

}

return total;

Decimal to Binary

Quote:

//Setup Variables

var orig,total,array;

orig=real(argument0)

array[8]=false

//Finding/Assigning Values

for(i=7;i>=0;i-=1)

{

check=power(2,i)

if orig>=check

{

orig-=check

array=true

}

}

//Putting Values in String

total=""

for(i=7;i>=0;i-=1)

{

if array=true

total+="1"

else

total+="0"

}

dec=argument0

return total;

I could have made the scripts smart enough to be able to take any length of numbers, but, whatever.

Playcount: 7723 at time of blog

Comments

F1ak3r 15 years, 9 months ago

You've been played! *snicker*

Bryan 15 years, 9 months ago

Optimize it.

SquareWheel 15 years, 9 months ago

I could probably take out half the variables, skip some if checks, and maybe even use less loop iterations, but hey, it's longer code this way, and so my blog has more content! =D

s 15 years, 9 months ago
Cpsgames 15 years, 9 months ago

Looks good.

sirxemic 15 years, 9 months ago

Binary to Decimal

Quote:
var in,out,len,i,bit;

in = string(argument0);

out = 0;

len = string_length(in);

for (i=len;i>=1;i-=1) {

bit = real(string_char_at(in,i));

out += bit<<(i-1);

}

return out;

Decimal to Binary

Quote:
in = real(abs(argument0));

if (in==0) return "0";

out = "";

mx = floor(ln(in)/ln(2));

for (i=0;i<=mx;i+=1) {

out = string(1&(in>>i))+out;

}

return out;

SquareWheel 15 years, 9 months ago

Your Binary to Decimal's look very similar to Xot's C-Ator, although yours looks a little more efficient.

Quote:
var bin,dec,l,p;

bin = argument0;

dec = 0;

l = string_length(bin);

for (p=1;p<=l;p+=1) {

dec = dec << 1;

if (string_char_at(bin,p)=="1") dec = dec | 1;

}

return dec;

And his Decimal to Binary

Quote:

var dec,bin;

dec = argument0;

if (dec) bin = "" else bin="0";

while (dec) {

bin = string_char_at("01",(dec & 1) + 1) + bin;

dec = dec >> 1;

}

return bin;

s 15 years, 9 months ago

C-Ator's use of len could be dropped