Programming Tips - C/C++: Convert a number to a string of its binary representation

Date: 2006Dec3 Update: 2025aug21 Language: C/C++ Keywords: to_binary, binary Q. C/C++: Convert a number to a string of its binary representation A. The routine ToBinary() below does it. Here is an entire working test program:
#include <string.h> #include <cstddef> #include <cstdio> // First, a helper function inline char *Shuffle(char *dest, const char *src) { return (char *) memmove(dest, src, strlen(src) + sizeof(char)); } void ToBinary(const int number, char *buf, const size_t size) { int n = number; int remaining = size - 1; buf[0] = '\0'; for (;n > 0; n >>= 1) { Shuffle(buf + 1, buf); buf[0] = '0' + (n & 1); remaining--; if (remaining <= 0) break; } } int main() { // Example Use char buf[100]; const int number = 256; ToBinary(number, buf, sizeof(buf)); printf("Decimal %d is %s binary\n", number, buf); }
Produces:
Decimal 256 is 100000000 binary