home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The C Users' Group Library 1994 August
/
wc-cdrom-cusersgrouplibrary-1994-08.iso
/
listings
/
v_02_02
/
2n02068a
< prev
next >
Wrap
Text File
|
1990-12-18
|
2KB
|
78 lines
/*
* File: ltobplus.c
* Creator: Blake Miller
* Version: 00.00.00 August 1990
* Modified: by Leor Zolman, Oct 90
* Language: Microsoft Ouick C Version 2.0, Turbo C/C++
* Purpose: Format String Function Test Program
* Convert Long, Int, or Char to a Binary string.
*/
#include <stdio.h>
#include <stdlib.h>
char *ltobplus ( long data, char *s,
int msbit, int lsbit,
int schar, int cchar );
/*
* Test program for ltobplus() function:
*/
void main ()
{
char sbuf[48];
char tchr = 0x0F;
int tint = 0x0A0A;
long tlng = 0xF0F0F0F0;
printf ( "\nDemonstrate <Data> -> <Binary String>\n");
printf ( "Convert 0x0F into binary string: %s\n",
ltobplus (tchr, sbuf, 8, 0, '1', '0' ));
printf ( "Convert 0x0A0A into binary string: %s\n",
ltobplus (tint, sbuf, 16, 0, '1', '0' ));
printf ( "Convert 0xF0F0F0F0 into binary string: %s\n",
ltobplus (tlng, sbuf, 32, 0, '1', '0' ));
tchr = 0xAA;
printf ( "Convert 0xA0 into binary string: %s\n",
ltobplus (tchr, sbuf, 8, 0, 'H', 'L' ));
}
/*
* Function ltobplus
*
* Binary string converter
* Convert from a number into a 'binary' string.
* That is, convert a byte, int or long into a string
* with specified characters representing '0' and '1'.
*
* Parameter s points to a caller-supplied destination buffer
* for the result string. The function returns a pointer
* to this buffer.
*/
char *ltobplus (long data, char *s,
int msbit, int lsbit,
int schar, int cchar)
{
char *saves = s; /* save start position */
unsigned long mask; /* bit select mask */
unsigned long sbit; /* start bit */
unsigned long ebit; /* end bit */
*s = '\0'; /* clear string */
sbit = (long) 0x01 << (msbit - 1); /* set start bit */
ebit = (long) 0x01 << lsbit; /* set end bit */
for (mask = sbit; mask >= ebit; mask >>= 1)
*s++ = (char) ((data & mask) ? schar : cchar);
*s = '\0';
return saves; /* return ptr to result */
}