Banka Don
Banka Don

Reputation: 43

How to convert big decimal numbers to binary without using itoa?

I've been working on a program that converts UTF-16 to UTF-8, but I've been having trouble converting big numbers like 14846106 to binary. All binary converters that I found on the web break if the decimal number is 4 digits or more. I used itoa, worked flawlessly but problem arose when I tried to compile the program on Linux. So are there any other alternatives (besides snprintf which isnt even capable of converting from decimal to binary)?

Upvotes: 0

Views: 119

Answers (1)

chux
chux

Reputation: 153367

A simple recursive to binary algorithm.

to_binary(unsigned x) {
  if (x > 1) {
    to_binary(x/2);
  }
  putchar(x%2 + '0');
}

Upvotes: 2

Related Questions