Hello, im new to C and I'm stuck with a program.

I now use this code to change some numbers

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define relays 8

int main(int argc, char *argv[]){
int relay = 0;
		
		if (strtol(argv[argc-1], NULL, 10))
		{
			if (strlen(argv[argc-1]) <= relays)
			{
				int a;
				for ( a = 0; argv[argc-1][a]; ++a )
			{
				int x = 1 << (argv[argc-1][a] - '1');
				relay += x;
			}
				printf("relay = %d\n", relay);
		}

(thanks to Dave Sinkula for the code)


it changeing the numbers like this:
1=1
2=2
3=4
4=8
5=16
6=32
7=64
...........

If it several numbers it adds the numbers together like 145 = 25 (1+8+16) and 134567 = 117 (1+4+16+32+64)

What i need is a function to do the opposite, like:

1=1
2=2
3= 1+2
4=3
5=1+3
6= 2+3
7=1+2+3
8=4
...........

Any ide how it could be done?

Looks like bits to me again.

#include <stdio.h>

void foo(int value)
{
   int i;
   printf("%d : ", value);
   for ( i = 0; i < 8; ++i )
   {
      if ( value & (1 << i) )
      {
         printf("%d ", i + 1);
      }
   }
   putchar('\n');
}

int main(void)
{
   int i;
   for ( i = 1; i <= 8; ++i )
   {
      foo(i);
   }
   return 0;
}

/* my output
1 : 1 
2 : 2 
3 : 1 2 
4 : 3 
5 : 1 3 
6 : 2 3 
7 : 1 2 3 
8 : 4 
*/

You are a genius, thank you so much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.