Usenet.com

www.Usenet.com

Group Index

Comp Thread Archive from Usenet.com

<-- __Chronological__ --> <-- __Thread__ -->

Re: error in hh length modifier when used with sscanf



In the "standard C library" documentation provided with lcc, there is no
separate description of the format spec for input vs output, so you have to
guess a bit. But it says "hh means unsigned char or signed char" which would
lead me to believe that when used in scanf only one byte is stored (assuming
a char is one byte on the machine you're compiling to).

In the ISO/IEC 9899 C spec it says specifically for fscanf:

hh   Specifies that a following d , i , o , u , x , X , or n conversion
specifier applies to an argument with type pointer to signed char or
unsigned char.

which seems pretty explicit that the target of the input can be a single
byte if that's what char is.

What am I missing here?

If hh can't do it, then how can I do an unsigned numeric input conversion
and put the result into a single byte? Of course, I could read into an int
and then copy it to a char, but I was hoping to be more efficient than that.

Bill Bennett

"CBFalconer" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Bill Bennett wrote:
> >
> > unsigned char buffer[] = "$$$$$$$$";
> > for (int i=0; i<8; i++) printf("%6x ", buffer[i]); printf("\n");
> > sscanf("55", "%hhx", buffer+2);
> > for (int i=0; i<8; i++) printf("%6x ", buffer[i]); printf("\n");
> >
> > I expect
> >     24     24     24     24     24     24     24     24
> >     24     24     55     24     24     24     24     24
> > but I get
> >     24     24     24     24     24     24     24     24
> >     24     24     55       0       0       0     24     24
> >
> > In other words, I expected one byte to be stored but instead 4
> > are stored, trampling adjacent bytes.
> >
> > Using %hx instead of %hhx has the correct result, only 2 bytes
> > are stored.
> >
> > Seems like an error in how the hh is handled, right?
>
> WRONG.  You got what you asked for.  Look up the meaning of hh in
> C99 (it is new since C90).  You are lucky you didn't get some sort
> of bus alignment violation, so it would appear you are using
> something x86 based, with sizeof(int) == 4 and sizeof(short) == 2
> that stores integers low byte first.
>
> -- 
> Chuck F ([EMAIL PROTECTED]) ([EMAIL PROTECTED])
>    Available for consulting/temporary embedded and systems.
>    <http://cbfalconer.home.att.net>  USE worldnet address!
>





<-- __Chronological__ --> <-- __Thread__ -->


Usenet.com



Please check out one of the premium Usenet Newsgroup Service Providers below for access to Usenet.