Dave's Brain

Browse - programming tips - to binary

Date: 2006Dec3, 2007Jan16
Language: C/C++

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;
	}
}

// Example use
main()
{
	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, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.