hi,
I have successfully converting the decimal to binary numbers in C (using char) but my intention is to make sure that it will convert to 12-bits binary numbers. For example, if decimal value is 10, then binary should be 000000000110 instead of only 110. Can anyone helps?
Computers do not store numbers in any format but binary, and whether the numbers are stored MSB->LSB or LSB->MSB is processor dependant. A decimal format means that a character string is representing the number as a base 10 number. You are asking to represent the binary number in a character format using only the characters '0' and '1', and to leave leading blanks as '0'. This code was written using DevC as a C project:
Code:
//******************************************
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
short i;
char b[12];
short num = 0x036e;
for( i = 11; i >= 0; i--)
{
if( (1 << i) & num)
b[11 - i] = '1';
else
b[11 - i] = '0';
}
b[12] = 0; // ascii terminating character
printf("\n %d %x %s\n", num, num, b); // decimal, hex, binary formats
system("PAUSE");
return 0;
}
//***********************************************
thanks for example. anyway, i had tried to modify the codes to fit with the 36-bits but unfortunately the outputs of binary numbers only give upto 32-bits and will repeat the first four LSB bits into the last four MSB bits (bit 35 to 32). sample of modify codes as follows:
#################################
int main (int argc, char *argv[])
{
short i;
char b[36];
then i had try to change the declaration of an integer to the long int (as shown below):
###########################
int main (long long int argc, char *argv[])
{
long long int i;
char b[36];
I remember doing something simliar at uni a decade or so ago. The easiest way to do the conversion is to perform a modulus divide by two in a loop, this won't give you the required word length, but adding a few 0's to the biginning of the number is pretty trivial.
edit: just noticed it is the adding 0's that you're having trouble with.
look up concatenation for a start, and maybe bit-masking. There are many ways to do this.
Here is the best solution for any positive integer from 0 to 32767
#include<conio.h>
main()
{
int n=0,i=0,j=0;
int a[31];
clrscr();
printf("\nenter the number \n");
scanf("%d",&n);
do
{
for(i=0;i<32;i++)
{
a=n%2;
n=n/2;
}
}while((n%2)!=0);
for(i=31;i>=0;i--)
{
printf("\nthe contents are %d",a);
}
getch();
}