2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
27
Task/Binary-digits/C/binary-digits.c
Normal file
27
Task/Binary-digits/C/binary-digits.c
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
char *bin(uint32_t x);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
for (size_t i = 0; i < 20; i++) {
|
||||
char *binstr = bin(i);
|
||||
printf("%s\n", binstr);
|
||||
free(binstr);
|
||||
}
|
||||
}
|
||||
|
||||
char *bin(uint32_t x)
|
||||
{
|
||||
size_t bits = (x == 0) ? 1 : log10((double) x)/log10(2) + 1;
|
||||
char *ret = malloc((bits + 1) * sizeof (char));
|
||||
for (size_t i = 0; i < bits ; i++) {
|
||||
ret[bits - i - 1] = (x & 1) ? '1' : '0';
|
||||
x >>= 1;
|
||||
}
|
||||
ret[bits] = '\0';
|
||||
return ret;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue