Hello all,
Excuse me if this has already been asked alot-but I did Google it and have done research-but alot of the snippets I've found don't work properly.
I want to convert a decimal integer to a binary number. I used atoi() to convert the user's input to an integer but now I want to convert that integer to binary.
Advice, code, etc. would be great.
2 replies to this topic
#1
Posted 13 January 2011 - 10:30 PM
|
|
|
#2
Posted 13 January 2011 - 11:30 PM
#include <iostream>
#include <string>
#define BITS_IN_INT (8*4)
//post-condition : delete is used on returned pointer
std::string* CreateBinaryString( int number );
int main()
{
using namespace std;
string* str = 0;
for( int i = 0; i < 10; i++ )
{
str = CreateBinaryString( i );
cout << i << "\t" << *str << "\n";
delete str;
}
return 0;
}
std::string* CreateBinaryString( int number )
{
char str[BITS_IN_INT+1];
for( int i = 0; i < BITS_IN_INT; i++ )
{
str[BITS_IN_INT-i-1] = ((number) & (0x0001<<i))? '1':'0';
}
str[BITS_IN_INT] = '\0';
std::string* ret = new std::string(str);
return ret;
}
josh@josh-desktop:~/Desktop$ g++ PrintBinary.cpp josh@josh-desktop:~/Desktop$ a.out 0 00000000000000000000000000000000 1 00000000000000000000000000000001 2 00000000000000000000000000000010 3 00000000000000000000000000000011 4 00000000000000000000000000000100 5 00000000000000000000000000000101 6 00000000000000000000000000000110 7 00000000000000000000000000000111 8 00000000000000000000000000001000 9 00000000000000000000000000001001
#3
Posted 14 January 2011 - 05:13 AM
Or if you prefer to use C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BITS_IN_INT (sizeof(int) * 8)
char* CreateBinaryString(int number);
int main(void) {
int i;
char* str;
for(i = 0;i < 10; i++) {
str = CreateBinaryString(i);
printf("%i\t%s\n", i, str);
free(str);
}
return 0;
}
char* CreateBinaryString(int number) {
char str[BITS_IN_INT+1];
int i;
for(i = 0; i < BITS_IN_INT; i++) {
str[BITS_IN_INT-i-1] = ((number) & (1 << i)) ? '1':'0';
}
str[BITS_IN_INT] = '\0';
char* ret = (char*) malloc(BITS_IN_INT + 1);
strncpy(ret, str, BITS_IN_INT + 1);
return ret;
}
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









