0

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?

2
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by stage
0

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 
*/
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.