Reputation: 23
I have a task to convert decemiacal number to 8-binary. from 1 to 100, i don't know how to reverse dights in right order/ i use recursive, i mean output is: 3 4 1, what it should be 1 3 4/ How to reverse a few numbers)
#include <math.h>
#include <stdio.h>
int bit8(int n) {
int x = n;
if (n == 100) {
return 1;
}
int mass[100];
int b;
int i = 0;
printf("%d: ", n);
while (x >= 8) {
b = x % 8;
x = x / 8;
}
if (x < 8) {
printf("%d ", x);
i++;
}
bit8(n + 1);
}
int main() {
int n = 1;
bit8(n);
}
Upvotes: 0
Views: 43
Reputation: 153348
to convert
decemiacalnumber to 8-binary
Suggest starting over.
Typical recursion first tests before maybe recursing.
To print an n-bit integer number:
void print_n_bit(unsigned value, unsigned bit_count) {
if (bit_count > 0) {
if (bit_count > 1) {
// Print the other, more significant, bits first.
print_n_bit(value >> 1, bit_count-1); // Recursive call
}
// Now print the least significant bit
putchar((value & 1) + '0');
}
}
Usage example:
int main(void) {
unsigned n = 1;
unsigned bits_to_print = 8;
print_n_bit(n, bits_to_print);
}
Upvotes: 1