GNK
GNK

Reputation: 1088

Get last two characters from char array elements

Trying to print the array elements, like below

typedef struct Info
{
char MacAdd[2];                      
} Info;

char MAC[100];

sprintf(MAC, "%x:%x%c", Info->MacAdd[0], Info->MacAdd[1],'\0');

printf("MAC %s",MAC);

Got output is --> ffffff98:ffffffa4

How can get output like ---> 98:a4

Upvotes: 0

Views: 294

Answers (1)

Steve Summit
Steve Summit

Reputation: 47933

The MacAdd array in your Info structure is declared as an array of char. But char is usually a signed type.

When you call printf, certain "default argument conversions" take place. Among other things, type char is promoted to int. And since 0x98 as a signed char is actually negative (it's -104), it is automatically sign extended when that happens -- that's where the extra ff's come from. The value ffffff98 is the 32-bit signed version of -104, so the value has been preserved.

There are at least three ways to fix this, in what I'd consider the order of most to least attractive:

  1. Redeclare the MacAdd array as an array of unsigned char.
  2. Change the printf format to "%hhx:%hhx". The hh tells printf that your value was originally a char, and this asks printf to undo the promotion and, in effect, strip the unwanted ff's back off.
  3. Change the call to sprintf(MAC, "%x:%x", Info->MacAdd[0] & 0xff, Info->MacAdd[1] & 0xff);

As @Aconcagua points out in a comment, once you get rid of the ff's, you will probably also want to tweak your printf format a little bit more, to take care of single-digit addresses.


Footnote: Solution 3 above is reasonably terrible, and I wouldn't seriously recommend it. It's what we used to use back in the days of Ritchie's original C compiler, when neither unsigned char nor %hhx had been invented yet.

Upvotes: 1

Related Questions