-3

I'm looking to convert an integer representation of binary into a string. i'm not allowed to use bitwise operations. when i converted the decimal integer value into that integer binary representation, i could've put the digits in a string and reverse, but i'm searching for a more elegant way.

Any ideas?

Atalia.d
  • 131
  • 1
  • 13
  • 1
    actually, all the numbers are represented in binary at CPU level, means when you type `int a = 5`, the value of `a` is viewed as `101`. unless you provide an example, this question is not clear. – ThunderWiring Nov 19 '16 at 08:10
  • You are confused. An integer is not binary (or octal, or decimal). It can be *represented* in binary (or octal), or in English (e.g. `five` is the same as `0b101` in binary, or `5` in decimal). – Basile Starynkevitch Nov 19 '16 at 08:21

1 Answers1

3

If you can't use bitwise operators just divide by 2 and check the reminder, you don't need to reverse the string if you use a fixed size (i.e. 32), something like:

/* Only for positive numbers */

char bin[] = "00000000000000000000000000000000";
int count = 31, num = 25;

while (num) {
    if (num % 2) bin[count] = '1';
    num /= 2;
    count--;
}
printf("%s\n", bin);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94