-
decimal to binary
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;
}
-
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
-
Can't you use itoa() to do that?
-
Oh.... that's right, you can :)
Code:
#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);
}
-
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 :)
-
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; ?
-
Code:
int *p = new int;
int *y = new int[50];
delete p;
delete[] y;
-
IIRC there is no need to delete the buffer since it is freed once the program ends??
-
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!!
-
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 = .....
}
-
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.