[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C help plz..



On Thu, Mar 16, 2000 at 03:04:53PM +1100, Shao Zhang wrote:
> Hi,
> 	If I have an unsigned long int, instead printing out its values
> 	in string using printf("%ld\n", my_var),
> 
> 	I would like to print it out as a 4-byte binary data. Is there
> 	any easy way to do this in C.
> 
> 	Thanks.
> Shao.

I pulled this out of a text book I have (modified from ints to longs):


#include <stdio.h>
#include <limits.h>

void 
bit_print_long(long l)
{
	long	i;
	long	n = sizeof(long) * CHAR_BIT;
	long	mask = 1 << (n - 1);

	for(i=1; i<=n; ++i) {
		putchar(((l & mask) == 0) ? '0' : '1');
		l <<= 1;
		if (i % CHAR_BIT == 0 && i < n)
		  putchar(' ');
	}
}

int
main(void)
{
	long	num = 2345687L;

	printf("Number %d is ", num);
	bit_print_long(num);
	putchar('\n');

	return 0;
}

-- 
+----------------------------------------------------+
| Eric G. Miller                        egm2@jps.net |
| GnuPG public key: http://www.jps.net/egm2/gpg.asc  |
+----------------------------------------------------+


Reply to: