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


3 Comments  →
   by Dost Muhammad Shah    3 Comments  →

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
RECOMMENDED READ  How to Turn a Raspberry Pi into NVR or DVR With Motion

Leave a comment
  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 Reply

Leave a Reply