In < >
(James Kuyper) writes:
>CBFalconer <> wrote in message news:<>...
>> Bill Bennett wrote:
>> > "CBFalconer" <> wrote in message
>> > > 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.
>...
>> > 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.
>>
>> There appears to be a conflict here between N869 and the summaries
>> on <http://www.dinkumware.com>. This may be an error in N869 that
>> has been revised in the actual standard. The proper place to
>> thrash this out is on comp.lang.c and comp.std.c. followups and
>> cross-posts set.
>
>As far as I can see, both n869.pdf and the final standard say the same
>thing, that "%hhx" is for reading in a single unsigned char in
>hexadecimal format. How are you reading them to allow four bytes to
>get trashed?
The undefined behaviour in the printf calls can explain *anything*,
doesn't it? %x expects unsigned int, while buffer[i] most likely gets
promoted to signed int.
There would have been a lot less traps in the C language if *all* the
shorter unsigned types got promoted to unsigned int. Preserving both
value and signedness makes a lot more sense than preserving value only.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: