Davey wrote:[color=blue]
>
> How do I display an integer in binary format in C?
>
> e.g. 4 displayed as "100"[/color]
Here's one common way to do it:
1) reserve enough storage for a string that can contain the whole
result.
If your integer is an unsigned long int, say, then you know that it
can't have more than sizeof(long int) * CHAR_BIT value bits, so just
define an array of char, sizeof(long int) * CHAR_BIT + 1 bytes in
length.
2) point to the start of the string.
3) if the number is even, write '0' through the pointer. Otherwise,
write '1' through the pointer.
4) increment the pointer.
5) divide the number by 2.
6) if the number is non-zero, continue from step 3).
7) write '\0' through the pointer, to null-terminate the string.
8) reverse the string, taking care to leave the terminator in place.
Davey wrote:[color=blue]
> How do I display an integer in binary format in C?
>
> e.g. 4 displayed as "100"
>
>[/color]
You should try it yourself.
void bits(uchar b, int n) {
for (--n; n >= 0; --n)
putchar((b & 1 << n) ? '1' : '0');
putchar(' ');
}
The above is not a program, but a clue.
--
Joe Wright mailto:joewwrig ht@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Davey wrote:[color=blue]
> How do I display an integer in binary format in C?
>
> e.g. 4 displayed as "100"
>
>[/color]
I thought this sounded familar, so I looked in my archives and sure
enough, there it was. I can't believe almost 11 years have gone by!
/*************** *************** *************** *************** ***/
/* File Id: bin.c. */
/* Author: Stan Milam. */
/* Date Written: 28-Apr-94. */
/* */
/* This program will print an unsigned integer value entered on*/
/* the command line in it binary format. */
/* */
/*************** *************** *************** *************** ***/
/*************** *************** *************** **************/
/* Check to see if command line args used. If not give tell*/
/* user how the program works. */
/*************** *************** *************** **************/
if ( argc < 2 ) {
fputs("Usage: BIN integer_number\ n", stderr);
return 1;
}
/*************** *************** *************** **************/
/* Determine the mask. Done this way to be portable. Also */
/* Extract the value from command line. */
/*************** *************** *************** **************/
/*************** *************** *************** **************/
/* For each possible bit determine its state and print. */
/*************** *************** *************** **************/
for ( i = 0; i < sizeof(unsigned ) * CHAR_BIT; i++ ) {
rv = (value & mask) >> (sizeof(unsigne d) * CHAR_BIT - 1);
value <<= 1;
printf("%d", rv);
}
Stan Milam wrote:[color=blue]
> Davey wrote:
>[color=green]
>> How do I display an integer in binary format in C?
>>
>> e.g. 4 displayed as "100"[/color]
>
> I thought this sounded familar, so I looked in my archives and sure
> enough, there it was. I can't believe almost 11 years have gone by!
>
> /*************** *************** *************** *************** ***/
> /* File Id: bin.c. */
> /* Author: Stan Milam. */
> /* Date Written: 28-Apr-94. */
> /* */
> /* This program will print an unsigned integer value entered on*/
> /* the command line in it binary format. */
> /* */
> /*************** *************** *************** *************** ***/
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <limits.h>
>
> int main( int argc, char **argv ) {
>
> unsigned value, rv, mask, i;
>
> /*************** *************** *************** **************/
> /* Check to see if command line args used. If not give tell*/
> /* user how the program works. */
> /*************** *************** *************** **************/[/color]
.... snip code ...
Here is something more generalized, with testing code. Also been
around a while in various guises.
/* Routines to display values in various bases */
/* with some useful helper routines. */
/* by C.B. Falconer, 19 Sept. 2001 */
/* Released to public domain. Attribution appreciated */
#include <stdio.h>
#include <string.h>
#include <limits.h> /* ULONG_MAX etc. */
/* =============== ======== */
/* reverse string in place */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;
lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */
/* =============== =============== ============== */
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
int hexify(unsigned int value)
{
static char hexchars[] = "0123456789abcd ef";
return (hexchars[value & 0xf]);
} /* hexify */
/* =============== =============== =============== ===== */
/* convert unsigned number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t basedisplay(uns igned long number, unsigned int base,
char *stg, size_t maxlgh)
{
char *s;
/* assert (stg[maxlgh]) is valid storage */
s = stg;
if (maxlgh && base)
do {
*s = hexify(number % base);
s++;
} while (--maxlgh && (number = number / base) );
*s = '\0';
revstring(stg);
return (s - stg);
} /* basedisplay */
/* =============== =============== =============== === */
/* convert signed number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t signbasedisplay (long number, unsigned int base,
char * stg, size_t maxlgh)
{
char *s;
size_t lgh;
unsigned long n;
s = stg; lgh = 0;
n = (unsigned long)number;
if (maxlgh && (number < 0L)) {
*s++ = '-';
maxlgh--;
n = -(unsigned long)number;
lgh = 1;
}
lgh = lgh + basedisplay(n, base, s, maxlgh);
return lgh;
} /* signbaseddispla y */
/* =============== ===== */
/* flush to end-of-line */
int flushln(FILE *f)
{
int ch;
while ('\n' != (ch = fgetc(f)) && (EOF != ch)) /* more */;
return ch;
} /* flushln */
/* ========== END of generically useful routines ============ */
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Peter Nilsson wrote:[color=blue]
> Stan Milam wrote:[color=green]
>> CBFalconer wrote:[/color]
>
> <snip>
>[color=green]
>> CB, keep it small, keep it simple, keep it readable and you
>> will be more productive and live longer.[/color]
>
> Any reason why you quoted the whole thing?
>
> Your post would be more productive if you pointed out the
> issue with LONG_MIN within CBF's code. ;)[/color]
What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.
--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
CBFalconer wrote:[color=blue]
> ...
> What issue? A value of LONG_MIN is immediately converted to an
> unsigned long with a '-' sign emitted.[/color]
The conversion of LONG_MIN to unsigned long may yield 0.
It's not likely to on any implementation in existance, but
the standard allows it. [Genuine strictly conforming itoa
functions have previously been posted to clc.]
Peter Nilsson wrote:[color=blue]
> CBFalconer wrote:[color=green]
>> ...
>> What issue? A value of LONG_MIN is immediately converted to an
>> unsigned long with a '-' sign emitted.[/color]
>
> The conversion of LONG_MIN to unsigned long may yield 0.
>
> It's not likely to on any implementation in existance, but
> the standard allows it. [Genuine strictly conforming itoa
> functions have previously been posted to clc.][/color]
I see no way for a non-zero integer to be converted to zero. Show
me. Remember that ULONG_MAX has to be odd, as implied by the
imposed weighted bit construction.
--
Some informative links:
news:news.annou nce.newusers
char* itoap(int val, int base)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base){
buf[i] ="0123456789abc def"[val % base];
printf("%c\n",b uf[i]);
}
return &buf[i+1];
}
"Davey" <davey@hello.co m> дÈëÏû
Ï¢ÐÂÎÅ:37p6inF5 e8reoU1@individ ual.net...[color=blue]
> How do I display an integer in binary format in C?
>
> e.g. 4 displayed as "100"
>[/color]
On Tue, 22 Feb 2005 19:14:52 +0800, Michael
<qq_qiutao@126. com> wrote:
[color=blue]
> 1. use lib function
>
> #include <stdlib.h>
> #include <stdio.h>
>
> int main(void)
> {
> int number = 4;
> char string[25];
>
> itoa(number, string, 10);[/color]
There is no such function in Standard C.
[color=blue]
> printf("integer = %d string = %s\n", number, string);
> return 0;
> }
>
>
> 2. write a function like itoa
>
> char* itoap(int val, int base)
> {
> static char buf[32] = {0};[/color]
How do you know that 32 characters is enough? It isn't, even with 32
bit values. The correct size should be something like:
#include <limits.h>
#define MAX_DIGITS (sizeof(val) * CHAR_BIT)
then define the buffer as
static char buf[MAX_DIGITS+1] = {0};
[color=blue]
> int i = 30;[/color]
and that should initialise i to MAX_DIGITS.
[color=blue]
> for(; val && i ; --i, val /= base){
> buf[i] ="0123456789abc def"[val % base];
> printf("%c\n",b uf[i]);
> }
> return &buf[i+1];
> }[/color]
Also, it would be a good idea to test base for being greater than 1 and
no greater than 16 and return some sort of error (possibly a null
pointer, possibly fill the buffer with stars, or just assert()).
Comment