Display Binary Equivalent To Decimal Value 
Author Message
 Display Binary Equivalent To Decimal Value

Hi!

Could someone PLEASE help me with this?
I'm looking for C sources to convert DECIMAL to BINARY representation...

So what I want is a program that gives me the correct BINARY equivalent for
a DECIMAL value I enter.

(131 = 10000011 etc...

--
Ltr!
  || Fluor

--
| Tell a man there are 300 billion stars in the universe and he'll believe you.
| Tell him a bench has wet paint on it and he'll have to touch to be sure.
|
| Linux: Reach Out And GREP SomeOne!



Sat, 08 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value

Quote:

>Could someone PLEASE help me with this?
>I'm looking for C sources to convert DECIMAL to BINARY representation...

>So what I want is a program that gives me the correct BINARY equivalent for
>a DECIMAL value I enter.

>(131 = 10000011 etc...

This is not a sources newsgroup really.

This destroys a, and prints the binary representation of a, the wrong way
round. (if you are European)

unsigned int a = 5050;

while (a)
{
    if (a & 1)
        printf("1");
    else
        printf("0");
    a>>=1;

Quote:
}



Sun, 09 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value
: Could someone PLEASE help me with this?  I'm looking for C sources to
: convert DECIMAL to BINARY representation...

: So what I want is a program that gives me the correct BINARY equivalent
: for a DECIMAL value I enter.

: (131 = 10000011 etc...

Here is a little program I wrote which works for hex values.  I am sure
you'll be able to modify to do decimals:

/* bits.c -- prints out a string of 0's and 1's to represent the
 * binary value of a hex number entered by the user.
 *
 * Written by:
 *      Paul D. Boyle
 *      Department of Chemistry
 *      North Carolina State University
 *      Raleigh, NC, 27695-8204
 *
 * Permission is specifically denied for this code or any derivation thereof
 * to be handed in as homework, either in part or as whole of the assignment.
 */

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

#define LINE_LEN 24

int main( void )
{
    unsigned int s;
    int j;
    char line[LINE_LEN],
         *ptr;

    int n_items = 0;

    do {
        n_items = 0;
        memset( line, '\0', sizeof(line) );
        fputs( "Enter hex value: ", stdout );
        fflush( stdout );
        if( NULL == fgets(line, sizeof(line), stdin) ) {
            fputs( "fgets() has a problem.\n", stderr );
            exit( EXIT_FAILURE );
        }
        if( NULL != (ptr = strchr(line, '\n')) ) *ptr = '\0';
        n_items = sscanf( line, "%x", &s );
    } while( n_items != 1 );

    fprintf( stdout, "Hex Value Entered: %#x\n", s );
    for( j = CHAR_BIT * sizeof(unsigned int) - 1; j >= 0; j-- ) {
         if( s & ( 1 << j) )
             printf( "%d", 1 );
         else
             printf( "%d", 0 );
         if( 0 == j % CHAR_BIT ) printf( " " );
         fflush( stdout );
    }
    puts( "\n" );

    exit( EXIT_SUCCESS );

Quote:
}  

--

Director, X-ray Structural Facility |   phone: (919) 515-7362
Department of Chemistry - Box 8204  |   FAX:   (919) 515-5079
North Carolina State University     |
Raleigh, NC, 27695-8204
http://laue.chem.ncsu.edu/web/xray.welcome.html


Sun, 09 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value
: Hi!

: Could someone PLEASE help me with this?
: I'm looking for C sources to convert DECIMAL to BINARY representation...

: So what I want is a program that gives me the correct BINARY equivalent for
: a DECIMAL value I enter.

: (131 = 10000011 etc...

: --
: Ltr!
:   || Fluor

: --
: | Tell a man there are 300 billion stars in the universe and he'll believe you.
: | Tell him a bench has wet paint on it and he'll have to touch to be sure.
: |
: | Linux: Reach Out And GREP SomeOne!

Funny thing you should ask, a friend of mine just recently asked me to do
exactly this for him -- here's what I came out with.  Assuming your system's
representation of unsigned int is 32 bits, this will show the binary
representation in 32 bits.
*NOTE* The obscure value on line 14 (2147483648) represents 1 * 2^31 or ONE 1
       followed by THIRTY ONE 0's.

<snip>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   unsigned int num;
   unsigned int i;

   if(argc < 2) {
      printf("Usage: %s <number to convert to binary>\n", argv[0]);
      exit(-1);
   }
   num = atoi(argv[1]);
   for(i=2147483648; i; i >>= 1) {
      if(num & i)
        printf("1");
      else printf("0");
   }
   printf("\n");
   return(0);

Quote:
}

<unsnip>

I hope this helps.
--
Sam J.
ralph7 AT cableregina DOT com



Sun, 09 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value
Hi root!

Quote:

> Hi!

> Could someone PLEASE help me with this?
> I'm looking for C sources to convert DECIMAL to BINARY representation...

> So what I want is a program that gives me the correct BINARY equivalent for
> a DECIMAL value I enter.

> (131 = 10000011 etc...

> --
> Ltr!
>   || Fluor

> --
> | Tell a man there are 300 billion stars in the universe and he'll believe you.
> | Tell him a bench has wet paint on it and he'll have to touch to be sure.
> |
> | Linux: Reach Out And GREP SomeOne!

Try this one.

#include <stdio.h>

int taulukko[17];
int luku, x = 2;
int i;

void main(void)
{
 printf ("Anna luku (0 lopettaa): ");
 scanf ("%i", &luku);
 printf ("\n");
 while (luku > 0)
 {
  for (i = 16; i >= 1; i--)
  {
   taulukko[i] = 0;
  }
  while (luku > 0)
  {
  if (luku % x) // tai  if(fmod(luku,x)) -> #include <math.h>
   taulukko[i] = 1;
  else taulukko[i] = 0;
   luku = luku / 2;
   i++;
  }
  for (i = 15; i >= 0; i--)
  {
   if ( i == 11 || i == 7 || i == 3)
   {
   printf ("  ");
   }
   printf ("%i ", taulukko[i]);
  }
 printf ("\n\nAnna luku (0 lopettaa): ");
 scanf ("%i", &luku);
 printf ("\n");
 }

Quote:
}

And buy finnish dictionary ;^)

Regards

--
Jarmo Tiittanen
Svanstr?minkuja 5-7 B22
00870 HELSINKI
http://www.dlc.fi/~jacxs




Sun, 09 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value
Groovy hepcat Jarmo Tiittanen was jivin' on Wed, 23 Jun 1999 23:47:29
+0300 in comp.lang.c.
Re: Display Binary Equivalent To Decimal Value's a cool scene! Dig it!

Quote:
>#include <stdio.h>

>int taulukko[17];
>int luku, x = 2;
>int i;

  Don't use global variables unless you actually need to. All of these
varaibles would have been better local to main(). Indeed, main() is
the only function in this program, so why would you need globals at
all?

Quote:
>void main(void)

  Now, Jarmo, you've been reading this group long enough to know
better than this! main() must return int, never void.

Quote:
>{
> printf ("Anna luku (0 lopettaa): ");

  You should flush the output with fflush() here if you don't want to
put a neline in the string.

  fflush(stdout);

Quote:
> scanf ("%i", &luku);

  scanf() is evil. See the FAQ.

Quote:
> printf ("\n");

  Unnecessary, when simply fputc('\n', stdout); would avoid all of
printf()'s variadic function argument parsing code, conversion code,
etc..

Quote:
> while (luku > 0)
> {
>  for (i = 16; i >= 1; i--)

  Huh? What? It's more usual to start from 0 and loop while the
incremented index variable is less than array length, ie.:

    for(i = 0; i < (sizeof taulukko / sizeof taulukko[i]); i++)

  Of course, looping "backward" does have its advantages sometimes. I
see what you're doing here. You're trying to find the right place in
the array at which to start storing 1s and 0s, right? Well, why don't
you say that? That's what comments are for, to allow others (or even
yourself later on) to figure out what's going on, when the code
doesn't speak for itself.

Quote:
>  {
>   taulukko[i] = 0;
>  }
>  while (luku > 0)
>  {
>  if (luku % x) // tai  if(fmod(luku,x)) -> #include <math.h>

  Don't use C++ style comments here. Many people hate them. Please use
proper C comments, beginning with /* and ending with */, when posting
here.
  Anyhow, the comment is not really useful. You don't want to use
fmod() since it is designed for floating point types, whereas you are
using integers. My advice is to just stick with the modulus operator,
or better still, the logical AND operator. For example:

    if(luku & 1)

Quote:
>   taulukko[i] = 1;
>  else taulukko[i] = 0;
>   luku = luku / 2;

  This could make "logically" more sense if shifted rather than
divided. The result is exactly the same, of course, but it just seems
more logical to me to shift luku. For example:

    luku >>= 1;

Quote:
>   i++;
>  }
>  for (i = 15; i >= 0; i--)
>  {
>   if ( i == 11 || i == 7 || i == 3)
>   {
>   printf ("  ");
>   }
>   printf ("%i ", taulukko[i]);
>  }
> printf ("\n\nAnna luku (0 lopettaa): ");
> scanf ("%i", &luku);
> printf ("\n");
> }

  And do remember to actually return a value:

  return 0;

Quote:
>}

  Here's a program I've just knocked off. It uses a function I wrote
some time ago, called binbyte(), which returns a pointer to a string
containing the binary representation of any 8 bit byte value (though
it can be adapted to suit any number of bits). I have written two
other functions that make use of binbyte(). These are called by
main(), which first determines whether the input is a number or a
string. (I know that's a little more than what was asked, but I just
couldn't resist a little embellishment. I get so bored sometimes.
Anyhow, it can be adapted to any need.) Most of this code is pretty
straight forward. A few lines take a little explaining, so I have
commented those lines. But if you need any more explanation, don't
hesitate to ask.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ENDIAN_MACHINE
/* comment out if your system is big endian, and leave uncommented for
li'l endian. (Eg., don't comment out if you use Intel based machine.)
*/

char *binbyte(unsigned char b)
{
  static char byte[9];
  char *nibble[] =
  {
    "0000",
    "0001",
    "0010",
    "0011",
    "0100",
    "0101",
    "0110",
    "0111",
    "1000",
    "1001",
    "1010",
    "1011",
    "1100",
    "1101",
    "1110",
    "1111"
  };

  strcpy(byte, nibble[b >> 4]);
  strcat(byte, nibble[b & 0x0f]);

  return byte;

Quote:
}

char *bininteger(void *data, size_t size)  /* works for any integer
type */
{
  char *buf;
  unsigned char *p = data;
  int i;

  if(data == NULL || (buf = malloc(size * 9)) == NULL)
    return NULL;

  *buf = '\0';

#ifdef ENDIAN_MACHINE
  for(i = size - 1; i >= 0; i--)  /* put bytes in the "right" order
for li'l endian machines */
#else
  for(i = 0; i < size; i++)
#endif
  {
    strcat(buf, binbyte(p[i]));
    strcat(buf, " ");
  }

  return buf;

Quote:
}

char *binarray(char *data, size_t length)  /* works for char array */
{
  char *buf;
  size_t i;

  if(data == NULL || (buf = malloc(length * 9)) == NULL)
    return NULL;

  *buf = '\0';

  for(i = 0; i < length; i++)
  {
    strcat(buf, binbyte(data[i]));
    strcat(buf, " ");
  }

  return buf;

Quote:
}

int main(void)
{
  unsigned n;
  char buf[100], *p, c;

  printf("Enter a number (0 or above) or a string\n"
  "(or just press ENTER to quit): ");
  fflush(stdout);

  while(fgets(buf, sizeof buf, stdin) && *buf != '\n')
  {
    if(NULL != (p = strchr(buf, '\n')))
      *p = '\0';        /* remove newline from the input */

    if(sscanf(buf, "%u%c", &n, &c) == 1)  /* test whether input is a
number, and only a number - else input is a string */
    {
      /* number */
      p = bininteger(&n, sizeof n);
      if(NULL == p)
      {
        fprintf(stderr, "Error converting to binary.\n");
        return EXIT_FAILURE;
      }
      printf("That number in binary is: %s\n\n", p);
    }
    else
    {
      /* string */
      p = binarray(buf, strlen(buf));
      if(NULL == p)
      {
        fprintf(stderr, "Error converting to binary.\n");
        return EXIT_FAILURE;
      }
      printf("That string in binary is:\n%s\n\n", p);
    }

    free(p);

    printf("Enter a number (0 or above) or a string\n"
    "(or just press ENTER to quit): ");
    fflush(stdout);
  }

  return 0;

Quote:
}
>And buy finnish dictionary ;^)

  Yes, and read it from start to... end. :)
--

----- Dig the EVEN NEWER, MORE IMPROVED news sig!! -----

-------------- Shaggy was here! ---------------
    http://aardvark.apana.org.au/~phaywood/
============= Ain't I'm a dawg!! ==============



Fri, 14 Dec 2001 03:00:00 GMT  
 Display Binary Equivalent To Decimal Value
Hi Peter!

Quote:

> Groovy hepcat Jarmo Tiittanen was jivin' on Wed, 23 Jun 1999 23:47:29
> +0300 in comp.lang.c.
> Re: Display Binary Equivalent To Decimal Value's a cool scene! Dig it!

> >#include <stdio.h>

> >int taulukko[17];
> >int luku, x = 2;
> >int i;

>   Don't use global variables unless you actually need to. All of these
> varaibles would have been better local to main(). Indeed, main() is
> the only function in this program, so why would you need globals at
> all?

I don't usually use global variables, but this ... happens now,because I
took one of my old school work and just send it without checked it out

Quote:
> >void main(void)

>   Now, Jarmo, you've been reading this group long enough to know
> better than this! main() must return int, never void.

Yes, you're right, bad mistake.

Quote:

> >{
> > printf ("Anna luku (0 lopettaa): ");

>   You should flush the output with fflush() here if you don't want to
> put a neline in the string.

>   fflush(stdout);

> > scanf ("%i", &luku);

>   scanf() is evil. See the FAQ.

Yes, I know, I have read FAQ. I use normally fgets or sscanf ...., they
are more safety.

Quote:

> > printf ("\n");

>   Unnecessary, when simply fputc('\n', stdout); would avoid all of
> printf()'s variadic function argument parsing code, conversion code,
> etc..

True, I have learnt this fputc and things like that here and I have
started using them.

Quote:

> > while (luku > 0)
> > {
> >  for (i = 16; i >= 1; i--)

>   Huh? What? It's more usual to start from 0 and loop while the
> incremented index variable is less than array length, ie.:

It doesn't matter, because it works ;^) Just a school work and we have to
do sometimes things as teachers want.

Quote:
>  Don't use C++ style comments here. Many people hate them. Please use
> proper C comments, beginning with /* and ending with */, when posting
> here.

Oh, I didn't know this comment style how I should use it here. I try to
mend my ways to proper uses.

Quote:
>   Anyhow, the comment is not really useful. You don't want to use
> fmod() since it is designed for floating point types, whereas you are
> using integers. My advice is to just stick with the modulus operator,
> or better still, the logical AND operator. For example:

>     if(luku & 1)

It's just some silly comment for me and it came out because qbasic uses
same function.

Quote:
>   This could make "logically" more sense if shifted rather than
> divided. The result is exactly the same, of course, but it just seems
> more logical to me to shift luku. For example:

>     luku >>= 1;

I haven't ever use shift thing, so I have to start practising it.

Quote:
>   And do remember to actually return a value:

I do.

Quote:
>   return 0;
> >}

>   Here's a program I've just knocked off. It uses a function I wrote
> some time ago, called binbyte(), which returns a pointer to a string
> containing the binary representation of any 8 bit byte value (though
> it can be adapted to suit any number of bits).

Nice code!

Quote:
> But if you need any more explanation, don't
> hesitate to ask.

I don't.

Quote:
> >And buy finnish dictionary ;^)

>   Yes, and read it from start to... end. :)

;^)

Next time it's better if I just check out what I'm sending there.
And maybe I should do some translations too.

Thanks your response and very good advices.

Regards

--
Jarmo Tiittanen
Svanstr?minkuja 5-7 B22
00870 HELSINKI
http://www.dlc.fi/~jacxs




Fri, 14 Dec 2001 03:00:00 GMT  
 
 [ 7 post ] 

 Relevant Pages 

1. Calculating the decimal equivalent of a given hex value

2. store ascii equivalent decimal value into array!!!!

3. Convert from binary to decimal, hex to decimal etc

4. Binary to Decimal function

5. Hexadecimal to binary, decimal in c#

6. Binary to decimal

7. Decimal, Hex, and Binary

8. decimal to binary

9. decimal to binary

10. binary to decimal question

11. conversion decimal<->binary

12. how to convert numbers in decimal to binary?

 

 
Powered by phpBB® Forum Software