Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print in binary format 2

Status
Not open for further replies.

italy

Programmer
Feb 13, 2001
162
US
how can I print an integer in binary format like is there any switch with printf or it has to be diffrent way .thanks


 
//this should work
//call:

printf("bin value:%s",iToBin(MyValue));

//using this:
//------convert an unsigned int to bin----------
char * iToBin(int val)
{
char *s_result= (char *)(malloc (16 * sizeof(char)));
char *s_buf = (char *)(malloc (16 * sizeof(char)));

strcpy(s_buf,"");
do
{
strcpy(s_result,((val%2)?"1":"0"));
strcat(s_result,s_buf);
strcpy(s_buf,s_result);
}while((val/=2)>=1);

return s_result;
}
jb
 
true.. sry
this should be better

instead of :
char *s_result= (char *)(malloc (16 * sizeof(char)));
use
char *s_result;

before :
return s_result;
add:
free(s_buf);
jb
 
Getting worse I'm afraid, now you're writing to an uninitialised pointer, with
strcpy(s_result,((val%2)?"1":"0"));
 
ok well sorry, im confused.. could u tell me how u would do it (well what to change in the code i pasted).. guess i need it:
jb

 
Here is how I would do it:
Code:
char *iToBin(int value)
{
    char *string = calloc(sizeof(int) * 8 + 1, sizeof(char));
    int i;
    for (i = 0; i < sizeof(int) * 8; i++)
        string[i] = (value & (1 << i)) ? '1' : '0';
    string[i] = '\0';
    return string;
}

//Daniel
 
Well I would do this, to store the result in a buffer
Code:
#include <stdio.h>
#include <limits.h>

/*
 * Note use of static store - the result must be used before calling
 * this function again.
 * This for example is wrong
 * printf( &quot;Result=%s %s\n&quot;, iToBin(0x0), iToBin(0xff) );
 */
char *iToBin( unsigned int val )
{
    static char result[CHAR_BIT*sizeof(unsigned int)+1];
    unsigned int mask = 1u << (CHAR_BIT*sizeof(unsigned int)-1);
    char *p = result;

    do
    {
        *p++ = val & mask ? '1' : '0';
    } while ( mask >>= 1 );    
    *p = '\0';
    return result;
}


int main ( ) {
    printf( &quot;Result=%s\n&quot;, iToBin(0x0u) );
    printf( &quot;Result=%s\n&quot;, iToBin(0x55u) );
    printf( &quot;Result=%s\n&quot;, iToBin(0xAAu) );
    printf( &quot;Result=%s\n&quot;, iToBin(0x12345678u) );
    printf( &quot;Result=%s\n&quot;, iToBin(0x87654321u) );
    return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top