Dave's Brain

Browse - Programming Tips - sprintf() can convert to decimal, hex and octal but not binary.

Date: 2006Dec3
Updated: 2007Jan16
Language: C/C++
Keywords: to_binary, binary

Q.  sprintf() can convert to decimal, hex and octal but not binary.
How do I do this?

A.  Here's a routine for you:

// 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; } } void ExampleUse() { char buf[100]; ToBinary(256, buf, sizeof(buf)) printf("256 is %s binary\n", buf); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.