PDA

Click to See Complete Forum and Search --> : decimal to binary


bob323
Jul 3rd, 2001, 12:27 AM
humm...
trying to convert decimal to binary but I'm a bit stuck I've been trying to do the following, but I want to assign it back to a variable, any ideas?


void ConvertToBinary(float &line){
int gpow=-1;
int rem;

//find the largest power of 2
while( pow (2, ++gpow) <= line);

//divide by the power of two
while (gpow >= 0){
line = line / pow (2, --gpow);
cout << floor( line);
}
cout << endl;

}

denniswrenn
Jul 3rd, 2001, 12:39 AM
The function doesn't properly convert from decimal to binary. Maybe you should fix that before trying to store the binary value(once you get it fixed, I'll write up some code that stores the number in a char*).

-D

Wynd
Jul 3rd, 2001, 01:37 AM
Can't you use itoa() to do that?

denniswrenn
Jul 3rd, 2001, 02:22 AM
Oh.... that's right, you can :)


#include <iostream.h>
#include <stdlib.h>
int main()
{
int dec = 5; //number to be converted
char* pcBuf = new char[15]; //make it 15 characters long, just incase somebody puts in 32767 (15 characters long, all 1's)
itoa(dec, pcBuf, 2); //convert int to ascii, with the base of 2
cout << pcBuf; //outputs 101
return(0);
}

parksie
Jul 3rd, 2001, 06:53 AM
Two things - make it 64 characters long in case somebody uses __int64 / longlong / long long / any other type. Second, delete[] the buffer when you've finished :)

denniswrenn
Jul 3rd, 2001, 12:19 PM
If they change the datatype, I guess they can change the size of the char* as well... BTW, how do you use delete[]? I tried using it a few times, but it resulted in error.... is it delete[] pcBuf; or delete pcBuf; ?

parksie
Jul 3rd, 2001, 12:21 PM
int *p = new int;
int *y = new int[50];

delete p;
delete[] y;

denniswrenn
Jul 3rd, 2001, 01:14 PM
IIRC there is no need to delete the buffer since it is freed once the program ends??

bob323
Jul 3rd, 2001, 01:59 PM
humm cool thanks that makes sense, didn't know about iota- good to know....
and yes an array will free at the end of program execution, but what if the program runs for weeks or months- ya might need that memory again!!

bob323
Jul 3rd, 2001, 02:31 PM
I wonder if there is a way that I can convert the array back
into a float so I can use it outside of this method....
any ideas?


void ConvertToBinary(float &line){
int power=0;

//find the largest power of 2 that will go into the number
while( pow (2, ++power) <= line);

//create an array of that size
char* pcBuf = new char[--power];

//convert float to ascii, with the base of 2
itoa(line, pcBuf, 2);

cout << pcBuf << endl;
//line = .....
}

parksie
Jul 3rd, 2001, 02:54 PM
You can't really convert a float to binary because you need to "represent" it in some way. Normally the IEEE sign/mantissa/exponent layout is used.