UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » a convert funtion

#1 2007-11-01 02:37 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: a convert funtion

oh,I want to implement a function to convert a integer to its binary value? how can I implement this function?
can anyone give me some ideas?thanks

Offline

#2 2007-11-01 11:28 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: a convert funtion

An integer is a binary value, so there's nothing to convert.

Or do you want to print out the binary value? Use %x to print out hexadecimals. If
you want to print out all the individual bits you need to loop over them and print out
a '0' or '1' manually, as far as I know there isn't an existing functions that does it
for you.

Offline

#3 2007-11-01 11:32 AM

zhn636
Member
Registered: 2007-04-24
Posts: 146

Re: a convert funtion

oh,thanks ,I  want to print out all the individual bits and I need to loop over them and print out every bit,how can I implement this function?
thanks

Offline

#4 2007-11-01 12:50 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: a convert funtion

Use shift and AND operations to select an individual bit (<< or >> and &).

Offline

#5 2007-11-01 01:34 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: a convert funtion

Yeah, it's kind of sad that after all these years, there's still no standard (or even
non-standard, that I know about) *printf() format for printing out in binary...  Yes,
sure, it's not often that useful (hex serves the same purpose much more compactly),
but still it's more useful than a lot of junk that gets added to the C standard all the
damned time...  I mean, you've got functions like strtol() that can PARSE binary (or
any arbitrary base), but no corresponding inverse function to produce such strings...
It's kind of stupid, really...

But, anyway, because I'm feeling generous, here's something to give you an idea:

void binout (int val)
{
    int     i;

    for (i = 31; i >= 0; i--)
        fputc ((val & (1 << i)) ? '1' : '0', stdout);
    fputc ('\n', stdout);
}

If working with longs or shorts, change "31" to match the appropriate highest bit
index for the size of that integer type on your system...  And, if you really wanted
to be spiffy, you'd make it not bother outputting all the leading zeros...  But, I'm not
going to do ALL your work for you (unless you pay me, anyway)... ;-)

Offline

  • Index
  • » C
  • » a convert funtion

Board footer

Powered by FluxBB