0

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.

user3794592
  • 183
  • 2
  • 16
  • 1
    I really don't see the point of using recursion in `binaryToAbits()`. A simple `for()` loop would have been much simpler, and probably a lot faster too. In any case, you could try adapting the answers to [this question](https://stackoverflow.com/q/111928/1679849). – r3mainer Jul 17 '17 at 11:46
  • You should really try to produce a minimal, complete, verifieable example (https://stackoverflow.com/help/mcve). Especially you should include explanation on what result you expect (and possibly also what you actually get). My test of your `binaryToAbits` gives reasonable results - yet you have indicated that this function behaves wrongly. – skyking Jul 17 '17 at 11:58
  • Can you provide an example of what your input looks like and what you want your output to look like? – Fabien Jul 17 '17 at 12:02

1 Answers1

3

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';
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63