Google Interview Question
Software Engineer / Developersint bin[20] = {0};
int dec = 0, rem = 0;
int i = 1;
cout<<"\n**** Converting a Decimal no to Binary ****\n";
cout<<"\n Enter the Decimal no: ";
cin>>dec;
while(dec>0){
rem = dec%2;
if(rem==1) //Case for odd numbers
bin[20] = 1;
bin[20-i] = rem;
dec = dec/2;
i++;
}
cout<<"\n No in Binary is: ";
for(int j=0; j<20; j++)
cout<<bin[j];
Come on, guys. This is C, not Java or C#.
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
if (argc < 2) {
printf("Give me a number.\n");
return 0;
}
int num = atoi(argv[1]);
printf("decimal: %d\n", num);
char bin[33];
memset(bin, '0', 32);
char* c = &bin[32];
*c = 0;
while (num) {
c--;
if (num & 1) *c = '1';
num = ((unsigned int) num) >> 1;
}
printf("binary: %s\n", c);
}
THIS CODE IS WORK FOR ALL WHETHER IT IS DECIMAL OR FLOAT
{
{
{
#include <iostream>
#include <string>
using namespace std;
int main()
{
float dec = 7.5;
string binary = "";
char *c=(char *)&dec;
int var_size=sizeof(dec); //calculate size of decimal number
for(int i=0;i<var_size;i++){ // loop to traverse each byte of number
char num = *c;
for(int x=0;x<8;x++) // find each bit in a byte
{
if ((num & 1) == 1)
{
binary = "1" + binary;
}
else
{
binary = "0" + binary;
}
num >>= 1;
}
c++;
}
cout << binary << endl;
getchar();
}
}
}
}
- Anonymous October 04, 2010