user3794592 user3794592 - 4 months ago 26
C Question

Convert int to byte for GPIO

I'm trying to convert a int to a 4 bit array, so that I can output them using the GPIOs of a raspberry pi. I'm programming in C. My current function is:

#include <stdio.h>

char *binaryToAbits(unsigned int answer, char *result) {
if(answer>1)
{
result=binaryToAbits(answer-1,result);
}
*result='0'+(answer & 0x01);
return result+1;
};

int main(void) {
unsigned int numToConvert=2;
char ascResult[]={0,0,0,0};
int i;
*binaryToAbits(numToConvert,ascResult)='\0';

for(i=0;i<4;i++)
{
if(ascResult[i]!='1') ascResult[i]='0';
}
for(i=3;i>=0;i--)
{
printf("%c\n",ascResult[i]);
}
printf("\n");
return 0;
}


The problem is that the signal for the array isn't calculated correctly.

Answer Source

Using recursion is making it more complicated than necessary.

You can simply do:

void binaryToAbits(unsigned int input, char *result)
{
    result[0] = (input & 0x1) ? '1' : '0';
    result[1] = (input & 0x2) ? '1' : '0';
    result[2] = (input & 0x4) ? '1' : '0';
    result[3] = (input & 0x8) ? '1' : '0';
}