GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 20-Dec-2006, 13:38
Saberwing Saberwing is offline
New Member
 
Join Date: Dec 2006
Posts: 4
Saberwing is on a distinguished road

Binary to Decimal Conversion


Hey there everyone.

I'm been trying to create a small little application that will convert numbers from decimal to binary, and then those binary values back to decimal. Eventually, there will be random values passed to the function, along with the total number of values passed--but for testing purposes I'm giving them both fixed values.

I'm compiling this using gcc in cygwin, and it seems to compile correctly, but the output that I'm currently receiving for the code shown below is:

The binary value of 20 is 10100
The binary value of 10 is 1010
The binary value of 400 is 110010000
The binary value of 2089 is 100000101001
The binary value of 1 is 1
The decimal value of 0 is,
The decimal value of 0 is,
The decimal value of 0 is,
The decimal value of 0 is,
The decimal value of 0 is, 1


As you can see, the function 'bindec' doesn't seem to be working...
and I'm completely at a loss to explain why! If anyone could give me a hand, I would be most appreciative. Apologies for the very long post, I didn't know how I could both shorten the code and still retain all of the information. Thanks again for your help and advice in advance!

Saberwing

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#define numberOfValues 5     /* this will become an argument passed to this function */

void decbin(int decimal, char *binary); /* Function Prototype */
void bindec(char binary[], int *decimal); /* Function Prototype */

void main(void)  // return type will be changed later

/* 'sort' is the primary method which is initially called. The input values and the number of
values to be sorted are passed here. As the memory required by the array is unknown, I have 
ensured through the use of my 'malloc' subroutine that 32 bytes of memory multiplied by the 
number of values passed to the 'sort' method are allocated. Initially,  sort then calls 'decbin' 
to convert the values in to binary form. Finally, 'bindec' is called, which will
reconvert the sorted numbers in to decimal form, so that they can be passed back correctly. */

// PROBLEM SEEMS TO LIE IN NOT PASSING DECIMAL VALUE CORRECTLY & THEN PRINTING IN TEST FUNCTION.

	{

		int inputValues[numberOfValues] = {20, 10, 400, 2089, 1};   /* will be replaced by ptr to input array eventually */
		int curValue;
		char *binary;

		binary = malloc(numberOfValues * 32);

		for (curValue = 0; curValue < numberOfValues; curValue++)
			decbin(inputValues[curValue], &(binary[curValue]));

		for (curValue = 0; curValue < numberOfValues; curValue++)
			bindec(&(binary[curValue]), &(inputValues[curValue]));

        return;

	}

void decbin(int decimal, char *binary)

/* This function converts a decimal value to binary by continuously updating the string 
of remainders, until eventually it is fully converted. This is achieved through the use 
of a do...while loop. The values are then entered in to an array and treated as a string. 
Because of this, it is easy to reverse the order of the values and construct the correct 
binary value of the number. */

	{

		int curBit = 31;
		int remainder;
		int i = 0; // for testing

		printf("The binary value of %d is ", decimal);

			do
			{
				remainder = decimal % 2;
				decimal = decimal / 2;
				binary[curBit] = remainder;
				curBit--;
			}
			while (decimal > 0);
			
		for ( ; curBit >= 0; curBit--)
			binary[curBit] = 0;

		while (binary[i] == 0)
			i++;
		
		for ( ; i < 32; i++)
			printf ("%d", binary[i]);
		
		printf ("\n");
		
        return;
        
	}

void bindec(char binary[], int *decimal)

	{
	
		int power(int counter); /* Function Prototype */
	
		int counter = 0;
		int curValue = 0;

		*decimal = 0;
		for (counter = 31; counter >= 0; counter--)
			{
				if (binary[counter] == 1)
					*decimal += power(counter);
			}
			
		for (curValue = 0; curValue < numberOfValues; curValue++)
			{
				int i;
				printf("The decimal value of %d is, ", binary[curValue]);

		for (i = 0; binary[curValue * 32 + i] == 0; i++);
		
				for ( ; i < 32; i++)
					printf ("%d", *decimal);
				printf ("\n");
			}

		return;

	}

int power(int counter)
	
/* This function is utilised to determine the total amount that is to be added to the 
previous decimal value. If the counter value passed to this function is already 0, then 
the value returned will default to 1. */

	{

		int twoPowered = 1;

		for( ; counter < 31; counter++)

			{
				twoPowered *= 2;
			}

		return twoPowered;

	}
  #2  
Old 20-Dec-2006, 15:03
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,641
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Binary to Decimal Conversion


Quote:
Originally Posted by Saberwing
CPP / C++ / C Code:

		for (curValue = 0; curValue < numberOfValues; curValue++)
			decbin(inputValues[curValue], &(binary[curValue]));
The first time through the loop you are storing the 32 binary digits in binary[0] through binary[31]. The second time, you are storing the 32 bits in binary[1] through binary[32], etc. In other words each time through the loop wipes out the previous values.

Maybe you can do something like the following::

CPP / C++ / C Code:
    for (curValue = 0; curValue < numberOfValues; curValue++) {
        decbin(inputValues[curValue], &(binary[curValue*32]));
    }

So that the bits of the first number are stored in binary[0] through binary[31], the bits of the second are stored in binary[32] through binary[63], etc.

Actually you might consider a 2-D array for the binary numbers (that's what I would probably do, but you can stick with 1-D arrays if you want to).

Then in your main() program after the decbin loop, you could do something like the following (I declared another int variable i.)


CPP / C++ / C Code:
    for (i = 0; i < numberOfValues; i++) {
        printf("inputValues[%d] = %d\n", i, inputValues[i]);
        printf("binary[%3d]: ", i * 32);
        for(curValue = i*32; curValue < (i+1)*32; curValue++) {
            printf("%d ", binary[curValue]);
        }
        printf("\n\n");
    }
    printf("\n");

So you might see something like this:

Code:
inputValues[0] = 20 binary[ 0]: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 inputValues[1] = 10 binary[ 32]: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 inputValues[2] = 400 binary[ 64]: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 inputValues[3] = 2089 binary[ 96]: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 1 inputValues[4] = 1 binary[128]: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

Now, to convert back to decimal:

CPP / C++ / C Code:
    for (curValue = 0; curValue < numberOfValues; curValue++) {
        bindec(&(binary[curValue*32]), &(inputValues[curValue]));
        printf("inputValues[%d] = %d\n", curValue, inputValues[curValue]);
    }

Of course, you are looking for
Code:
inputValues[0] = 20 inputValues[1] = 10 inputValues[2] = 400 inputValues[3] = 2089 inputValues[4] = 1

Regards,

Dave

Footnote: for my sample output lines above, I commented out the print statements inside the bindec and decbin functions (all printout is from main()). Of course for debugging purposes you can print out values anywhere that you need to in order to see what the program is working on. I printed out all 32 bits of the binary numbers, instead of doing the neat thing you did to suppress leading zeros. (I also spaced them out so that I could count them with my stubby, fat little fingers.)
  #3  
Old 20-Dec-2006, 15:36
Saberwing Saberwing is offline
New Member
 
Join Date: Dec 2006
Posts: 4
Saberwing is on a distinguished road

Re: Binary to Decimal Conversion


Brilliant! Thank you very much for the feedback, I'm very happy to see it finally working! The amount of time I've spent staring at this code...argh! I'll give the two dimensional arrays a shot. I'm pretty sure that the specification for the assignment says that they should be stored that way, so it'll probably be worth it to go out of my way to ensure that they are. Thanks again.
  #4  
Old 28-Dec-2006, 04:54
Saberwing Saberwing is offline
New Member
 
Join Date: Dec 2006
Posts: 4
Saberwing is on a distinguished road

Re: Binary to Decimal Conversion


Okay!...so I didn't get very far. I thought that I'd stick with the 1-dimensional array, only to have that come and kick me in the butt, as further down in the specification it states that a 2-dimensional array definitely needs to be used. I'm now having a very strange situation. I'll try to condense the code down as much as possible, but please don't forget to ask me if I've left anything out

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define numberOfValues 5     /* this will become an argument passed to this function */

void decbin(int decimal, int cellArray[][32], int curValue); /* Function Prototype */

void main(void)  // Will become ptr to input array and number of values

	{

		int inputValues[numberOfValues] = {20, 10, 400, 2089, 1};   /* will be replaced by ptr to input array */
		int curValue;
		int cellArray[numberOfValues][32];

//		cellArray = malloc(numberOfValues * 32);    malloc doesn't work on multidimensional arrays? maybe need an alternative.

		for (curValue = 0; curValue < numberOfValues; curValue++)
			decbin(inputValues[curValue], &(cellArray[curValue][32]), curValue);

         }

void decbin(int decimal, int cellArray[][32], int curValue)

/* This function converts a decimal value to binary by continuously updating the string 
of remainders, until eventually it is fully converted. This is achieved through the use 
of a do...while loop. */

	{

		int binBit = 31;
		int remainder;
		int i = 0; // for testing

		printf("The binary value of %d is ", decimal);

			do
			{
				remainder = decimal % 2;
				decimal = decimal / 2;
				cellArray[curValue][binBit] = remainder;
				binBit--;
			}
			while (decimal > 0);
			
		for (binBit; binBit >= 0; binBit--)
			cellArray[curValue][binBit] = 0;

		while (cellArray[curValue][i] == 0)
			i++;
		
		for ( ; i < 32; i++)
			printf ("%d", cellArray[curValue][i]);
		
		printf ("\n");
		
        return;
        
	}


The current output that I'm getting is that the first 3 are working correctly, and then an incorrect 4th print line loops forever:

'The binary value of 20 is 10100
The binary value of 10 is 1010
The binary value of 400 is 110010000
The binary value of 0 is
The binary value of 0 is
....etc etc.'

When I tried to play around with the code to see what was wrong, I discovered something interesting.

(By play around, I mean that I assigned curValue to 1 and and commented out the for loop calling the decbin function and inputted this in it's place: )

decbin(inputValues[1], &(cellArray[2][32]), 2);

The output now is

'The binary value of 10 is 1010
Segmentation fault (core dumped)'

The first print line that it gives me is obviously right, but it seems to HATE being passed the value 2! It doesn't do this for any of the other ones. Sorry again for the long post, but this has been driving me mad!

Thanks again for your help in advance.

Shahin

Edit: Also, is there any way of passing a 2 dimensional array to a method without having to pass both of the points along it? For example...decbin(&(cellArray[][curValue]) Excuse my poor use of programming terminology...I am but a student!
  #5  
Old 28-Dec-2006, 09:34
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,641
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Binary to Decimal Conversion


Quote:
Originally Posted by Saberwing
. I'm now having a very strange situation.

The following is incorrect. Didn't your compiler give a warning? I would like to know what compiler you are using and the exact compile time messages that you saw. (The reason that I ask is that you should learn which messages are significant, and this would be one of the significant ones.)

CPP / C++ / C Code:
    decbin(inputValues[curValue], &(cellArray[curValue][32]), curValue);
You are giving the address of a particular element each time through the loop.

The first time you are giving it the address of cellArray[0][32].
The second time you are giving it the address of cellArray[1][32], etc

but the function is defined like this:

CPP / C++ / C Code:
void decbin(int decimal, int cellArray[][32], int curValue)

So the function is expecting the array (that is, the address of the array), not the address of a particular element of the array. Note that the address of the array is, by definition the address of cellArray[0][0] (the first element of the array).
In function calls, you can just give it the name of the array, and the compiler will treat it as the address of the first element of the array:

CPP / C++ / C Code:
		for (curValue = 0; curValue < numberOfValues; curValue++)
			decbin(inputValues[curValue], cellArray, curValue);

Note that there is a bug in decbin that will cause a problem if you pass it a value of zero to convert, but by fixing the way that you call decbin, you should be able to print out your sample values OK. My recommendation would be to fix the first bug first. Then experiment with sending it a value of zero to convert to see if you see the other bug.

By the way, what the heck is this doing here?
CPP / C++ / C Code:
 #include <pthread.h>

I really recommend that you don't include any superfluous headers. If/when you get to the point that you need pthread.h, then put it in. (It's not a standard library header and some compiler distributions won't have it so the program wouldn't compile, and other people couldn't use your example to learn from.)

Regrds,

Dave
  #6  
Old 28-Dec-2006, 14:57
Saberwing Saberwing is offline
New Member
 
Join Date: Dec 2006
Posts: 4
Saberwing is on a distinguished road

Re: Binary to Decimal Conversion


Thank you very much for the help, once again!

There was a lot missing from my fundamental knowledge of arrays and pointers which you helped set straight.

Oh, and as for the pthreads, I have them elsewhere in the code but I was trying to cut all of the unnecessary stuff out and just write what didn't work--I seemed to have missed that bit! The 'difficult' part of this assignment starts tomorrow, so I'll be slaving away for a few hours at home on it then. It includes a lot of threading that I'm not so confident about, so no doubt, I'll be seeing you again very shortly...

Thanks again for the help--it's really appreciated. I'm learning and getting the assignment done, imagine that!

Shahin
 
 

Recent GIDBlogLast Week of IA Training by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Conversion: Binary, Decimal, Hexadecimal WaltP C Programming Language 1 10-May-2006 06:49
Decimal to binary conversion oozsakarya C Programming Language 3 17-Nov-2005 11:59
Hex Result giving strange answers. Rosdahale C Programming Language 6 07-Dec-2004 20:28

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:20.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.