Click to See Complete Forum and Search --> : converting Binary to Decimal with .c


Nameless
10-23-2001, 03:46 PM
Hey
I'm a rather novice .c programmer and I am trying to write a program to convert binarys (base 2) to decimal (base 10).
I was just wondering what kind of equasion I would use.
I know pretty much any calculator can convert bin to dec but I need the source code.......


Thanks

TheLinuxDuck
10-23-2001, 03:59 PM
I'm not all that good with math, so I tend to use brute force, as necessary. With that said, when I need to deal with binary numbers, I generally create a struct that uses 8 single bits, and then a union of that struct with an unsigned char.
http://www.codeexamples.org/cgi-bin/c2h/hl.cgi?type=HTMLdetail&filename=bits.c

This is a simple example that could be modified to do what you're wanting to do.

kmj
10-23-2001, 05:03 PM
http://delphi.about.com/library/weekly/aa010599.htm?terms=decimal+to+binary

This page has the algorithm in some language; vb, I think. It should be easy enough to translate it into C;


should looks something like the following, which I quickly copied out of some other code.

// make sure your string "chars" is at // bigger than n
trans_to_chars(uint val, char *chars) {
uint q = val;
uint r;

int n = 2;
while (q != 0) {
r = q % 2;
q = q / 1;
chars[n] = r + '0';
n--;
if (n < -1) { /*sanity check*/
printf("miscalculation in translation\n");
exit(0);
}
}
/* fill in rest w/ 'A', since they get value of 0 (leading zeroes)*/
while (n >= 0) {
chars[n] = 'A';
n--;
}
}

pinoy
10-23-2001, 07:13 PM
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>

int binary_to_decimal(const char *binary)
{
int dec, pos;
const char *ptr = binary + strlen(binary)-1;
for (pos = 0, dec = 0; ptr >= binary; pos++, ptr--) {
assert(*ptr == '0' || *ptr == '1');
if (*ptr == '1')
dec += (int)pow(2, pos);
}
return dec;
}

int main(void)
{
printf("%d\n", binary_to_decimal("101"));
printf("%d\n", binary_to_decimal("111"));
printf("%d\n", binary_to_decimal("1000"));
return 0;
}

bwkaz
10-23-2001, 08:28 PM
Or, pinoy, instead of adding pow(2, pos), just add (1 << pos) to dec. It does the same thing, and it does it in one step rather than "pos" steps (at least, I think that pow takes "pos" steps to execute).

And even if pow can do its thing in constant time (1 step), the shifting is faster anyway, because it's all integer math -- pow() is floating-point. Just make sure your string is less than 32 characters long, because if it's longer it'll overflow.

[ 23 October 2001: Message edited by: bwkaz ]

pinoy
10-23-2001, 11:12 PM
Originally posted by bwkaz:
<STRONG>Or, pinoy, instead of adding pow(2, pos), just add (1 &lt;&lt; pos) to dec. It does the same thing, and it does it in one step rather than "pos" steps (at least, I think that pow takes "pos" steps to execute).

And even if pow can do its thing in constant time (1 step), the shifting is faster anyway, because it's all integer math -- pow() is floating-point. Just make sure your string is less than 32 characters long, because if it's longer it'll overflow.

[ 23 October 2001: Message edited by: bwkaz ]</STRONG>

you're right bwkaz, that didn't come to mind when I wrote that thing quickly. I initially thought of '^' then realized that that was an xor operator and then I remembered pow(). The function was a quick and dirty hack, I don't expect anyone here to take my code and paste it to production code without hacking it first.

pinoy
10-23-2001, 11:12 PM
Originally posted by bwkaz:
<STRONG>Or, pinoy, instead of adding pow(2, pos), just add (1 &lt;&lt; pos) to dec. It does the same thing, and it does it in one step rather than "pos" steps (at least, I think that pow takes "pos" steps to execute).

And even if pow can do its thing in constant time (1 step), the shifting is faster anyway, because it's all integer math -- pow() is floating-point. Just make sure your string is less than 32 characters long, because if it's longer it'll overflow.

[ 23 October 2001: Message edited by: bwkaz ]</STRONG>

you're right bwkaz, that didn't come to mind when I wrote that thing quickly. I initially thought of '^' then realized that that was an xor operator and then I remembered pow(). The function was a quick and dirty hack, I don't expect anyone here to take my code and paste it to production code without hacking it first.

augur
10-24-2001, 04:48 AM
Greetings,

int bin2dec(char *bin) {
int d = 0, i, l = strlen(bin);
for(i=0;i&lt;l;i++)
(d &lt;&lt;= 1) |= (bin[i]=='0')?0:1;
return d;
}

Nameless
10-24-2001, 01:06 PM
I figured it out. A little more simple I find than your programs, but your examples set me on the right track. Thanks.

#include&lt;stdio.h&gt;

main()
{
unsigned char bin[9];
int dec,place,flag,ctr;
unsigned char more;


more='y';
while( more == 'y' || more == 'Y')
{
dec=0;
flag=0;

printf("\nEnter 8 bit binary number: ");
scanf("%s",bin);
fflush(stdin);

if (strlen(bin) != 8)
flag=1;

place=128;
ctr=0;
while(ctr &lt;= 7 && flag != 1)
{
if(bin[ctr]!='0' && bin[ctr]!='1')
flag=1;
else if(bin[ctr]=='1')
dec=dec+place;

place=place/2;
ctr++;

}

if(flag == 0)
{
printf("\n%d\n",dec);
}
else
{
printf("\nError. Invalid Binary Number. Please Try Again.");
}

more='x';
while(more != 'y' && more != 'n')
{
printf("\nPlay again?[y/n] ");
scanf("%c",&more);
fflush(stdin);

if (more != 'y' && more != 'n')
printf("\nY or N only!\n");
}
}
printf("goodbye");
}

kormoc
10-24-2001, 08:42 PM
Here is a very small, short program to convert from base 2 to ten:
This is all you need to do. And it is a lot faster then yours.
#include &lt;stdio.h&gt;

void main(void)
{
int x,y=2,t,i;
printf("Please enter the number: ");
scanf("%i",&x);
t=x%10;
i=y;
do
{
t+=x/10%10*y;
x/=10;
y*=i;
}
while(x&gt;10);
printf("\n%i\n",t);
return;
}

Nameless
10-24-2001, 10:32 PM
My program is dos based and converts from base 2 to 10.

Your program is cool but I haven't learned the 'do' command yet.

kormoc
10-26-2001, 01:41 AM
I wrote that for a friend a while ago
It works on any system.

do
{

}while(...)

does the while loop once before it checks the while condition, so

do
{

}while(1==2)

will still run the loop once.
Understand?

pinoy
10-26-2001, 06:24 AM
do { } while(0);

will run the loop once. Seems like a funny construct for a lot of people, but this is actually quite common, with macros especially. It is also used as a 'goto' by using break.

macros - consider an assert(expr) macro, it might be implemented as the code below (assuming int 3 is a debug break). We want to compile out assert on release builds, but have it present on debug builds


#ifdef NDEBUG
#define assert(expr) do { } while(0)
#else
#define assert(expr) do { if (!(expr)) __asm int 3; } while (0)
#endif


What the 'do { } while(0)' basically do is protect an unbracked if.

e.g.

if (x &gt; 5)
assert(x &lt; 100);
x++;


if the NDEBUG build is compiled, the following code evaluates as:

if (x &gt; 5)
do { } while(0);
x++;


Had we defined NDEBUG assert as:
#define assert(expr)
then you get the following bug:

if (x &gt; 5)
x++;


as a goto:


do {
if (!foo())
/* goto clean up */
break;
bar();
}
while (0);
/* clean up */
fclose(fp);
free(buf);
/* etc... */
return 0;

kormoc
11-02-2001, 02:11 AM
also, if you add a scanf for y and set y to a base of 2..10, it will convert base 2..10 to base 10. Simple.