1

I am programming in C and I have a character array filled with letters/numbers. I want to compare the first two values together as one number or combo.

char values[8];
//a value of this might be 245756
switch (values[0 and 1]){
   case 24:
     do something;
   case 45:
     do something else;
}

Do I have to concatenate or what if I want to combine the two values and then see if they equal some set of combinations?

Thanks!

Please let me know if I am being unclear.

0

5 Answers 5

1

I'm assuming that your char array holds the characters '2', '4', etc.

In which case, you can convert a character to its equivalent integer value as follows:

char x = '2';
int  y = x - '0';

So all you need to do is perform this calculation for each of values[0] and values[1], and then perform the base-10 maths to combine these into a single integer value.

If your char array already holds the integer value for each digit, then you can of course skip the conversion, and jump straight to the base-10 maths.

Sign up to request clarification or add additional context in comments.

Comments

1
switch ((values[0] - '0') * 10 + (values[1] - '0')]){

Comments

1

you can do the switch based on the following expression:

(values[0]-'0')*10 + values[1]-'0'

Comments

0

One way to do this would be to cast the array to a uint16_t pointer and dereference it (some people might disapprove of this on principle, though). You'd have to determine what numbers (as a two byte int) the combinations would form to set your case values, though. For example,

switch (*(uint16_t *)values) {
    case 0x4131: {    /* "1A" on little-endian systems */
  ...

Another way would be to form an int from the two characters in a simple expression and switch on it.

switch( ((int)values[0] << 8) | (int)values[1] ) {
    case ('1' << 8) | 'A': {
  ...

The ('1' << 8) | 'A' is ok for case since it can be evaluated at compile time.

Comments

-1
char values[8]="0123456";
switch ( (values[2]=0,atoi(values)) ){
   case 24:
     do something;
   case 45:
     do something else;
}

should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.