Can someone give me an idea to convert decimal numbers into its binary equivalent and store each binary in arrays in C programming language??
Conversion of decimal to binary in C programming n store in arrays
Collapse
X
-
In C, all the number types are, somewhere deep in your computer, actually stored as a row of binary bits, so I wouldn't call a number "decimal" unless it's decimal digits were stored in a string. But aside from that, to get a bit at a specific position in an int, you can make a int that has only a bit in the place in question, compare it to the original int with the bitwise and operator (so that the result has all false bits unless both the ints have a bit in the same position), and then cast the result to a bool. Hope this helps. -
i have idea for only one decimal numberOriginally posted by r035198xWhat ideas do YOU have for it yet?
that is input a number then the program gives you its binary equivalent
the code is as follows:
but that's only for one numberCode:int num,no_bits; printf("Enter number"); scanf("%d",&num); no_bits=count_bits(num); printf("number of bits %d",no_bits); bin_print(num,no_bits); count_bits(int n) //function to count number of bits { int i=0; for (;n!=0;n=n>>1) i++; return(i); } bin_print(int x, int n_bits) /* function to print decimal numbers in binary format */ { int j; printf("no. %d in binary \t",x); for(j=n_bits-1; j>=0;j--) printf("%i",(x>>j) & 01); }
i have to do it for a series of numbers stored in an array and store the binary ones in another arrayComment
-
There is a simple algorithm for this.
Given the number 22 which has these bits:
16 8 .. 4 .. 2 .. 1
1.. 0 .. 1 .. 1 .. 0
To see if the bit in the 4 position is set, divide the number by 4 and take the result %2. That is:
22/4 = 5 and 5%2 is 1 --> the 4 bit is set
22/8 = 2 and 2%2 is 0 --> the 8 bit is not set
No need for fancy bit shifting.Comment
-
My book C++ In Plain English by Brian Overland has an interesting function for this:
I presume the equivalent can be written in CCode:void print_binary(short input_field) { int i,bit_set; while (i<=16) { bit_set = ((Ox8000 & input_field) >0); printf("%d",bit_set); input_field = input_field << 1; i++;} }Comment
Comment