I have a number that I would like to convert to binary (from decimal) in C.
I would like my binary to always be in 5 bits (the decimal will never exceed 31). I alrea
int main() {
int n,c,k;
printf("Enter_an_integer_in_decimal_number_system:_");
scanf("%d",&n);
printf("%d_in_binary_number_system_is:_", n);
for (c = n; c > 0; c = c/2) {
k = c%2;
k = (k>0)? printf("1"):printf("0");
}
getch();
return 0;
}
My take:
char* to_bitstring(uint32_t val, char buffer[], int size) {
buffer[--size] = 0;
while (size > 0) {
buffer[--size] = (val % 2 ? '1' : '0');
val = val >> 1;
}
return buffer; /* convenience */
}
This will write SIZE characters to BUFFER:
char buffer[17];
printf("%s\n", to_bitstring(42, buffer, sizeof(buffer)));
And will print:
0000000000101010
One approach is this:
unsigned int x = 30;
char bits[] = "00000";
bits[4] = (x & 1) + '0';
x >>= 1;
bits[3] = (x & 1) + '0';
x >>= 1;
bits[2] = (x & 1) + '0';
x >>= 1;
bits[1] = (x & 1) + '0';
x >>= 1;
bits[0] = x + '0';
Probably not the most elegant approach...
For 31 values, instead of doing malloc to allocate a string, followed by the bit manipulation to fill it, you may just want to use a lookup table.
static const char *bitstrings[] = {
"00000", "00001", "00010", … "11111"
};
Then your conversion is as simple as return bitstrings[i]
. If you're doing this often, this will be faster (by avoiding malloc).
Otherwise, you don't really need any shifting (except to make writing your constants easier); you can just use bit-and:
char *bits = malloc(6);
bits[0] = (i & (1<<4)) ? '1' : '0'; /* you can also just write out the bit values, but the */
bits[1] = (i & (1<<3)) ? '1' : '0'; /* compiler should be able to optimize a constant! */
⋮
bits[6] = 0; /* null-terminate string*/
There is a (maybe) micro-optimization you can do if you assume ASCII, by using addition. You can also use a loop here, but I needed two lines for the comment :-P. Performance-wise, neither will matter. All the time is spent in malloc.
#include<stdio.h>
int mask = 1;
void decToBi(int);
void decToBi(int n){
for(int j=15;j>=0;j--){
int result;
result = n & (mask<<j);
if(result)
printf("1");
else
printf("0");
}
}
int main(){
int n;
scanf("%d",&n);
decToBi(n);
printf("\n");
return 0;
}
Hope this helps
Here is C program to convert decimal to binary using bitwise operator with any decimal supported by system and holding only the required memory
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
int n, t = 0;
char *bin, b[2] = "";
scanf("%d", &n);
bin = (char*)malloc(sizeof(char) + 2);
while (n != 0)
{
t = n >> 1;
t = t << 1;
t = n - t;
n = n >> 1;
itoa(t, b, 10);
bin = realloc((char*)bin, sizeof(char) + 1);
strcat(bin, b);
}
strrev(bin);
printf("\n%s\n", bin);
return 0 ;
}