function to return binary equivalent of an int in a string format

On request of Shamas Akhtar Awan :
This is the function to return a string of binary equivalent of an int. The function takes in an integer value and returns a string of 0′s and 1′s of binary equavalet of that integer.

char * int2binarystr(int value) {
    char binstr[23];// adjust the size of the string to your needs
    int i,b;
    b=value;
    i=0;
    while(b>0)
    {
        binstr[i]=b%2;
        b=b/2; i++;
    }
    binstr[i]=00;
    return binstr; // returns the string
}

You can use this in your code as needed. One example is to write to uart the string

Uart0_write_text(int2binarystr(20)); // writes the string conataing the binary equavalent of 20 to uart
 
Dost Muhammad Shah

Dost Muhammad Shah

Dost Muhammad specializing in Embedded Design, Firmware development, PCB designing , testing and prototyping. He enjoys sharing his experience with others .Get in touch with Dost on Twitter or via Contact form

 

3 thoughts on “function to return binary equivalent of an int in a string format

  1. One more doubt, in this line char * int2binarystr(int value) , what is the use of * , can u explain what happen if we don't write * …… I write function without * so can u explain this point

    1. The function returns a pointer to the string to which it will write the binary equivalent. If you skip * it will return a char value instead of pointer

Leave a Reply to Youstron sicCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.