zh*********************@gmail.com wrote:
Dear all,
I need you help.
here the program:
char a = 0x91;
printf("%x",a);
Well, no. That isn't anywhere close to being a program.
result: ff ff ff 91
Well, no. I don't believe those three embedded spaces for a minute.
>
now, i was confused with the result. I think it is 91. but it seems
convert to something.
why?
This results from (a) 'char' being signed on your implementation and
(b) sign extension when 0x91 has the same bit pattern as a negative
char, which then is promoted to a negative int when passed to printf.
The program below, which incorporates several things which should never
appear in well-written code, should illustrate the problem if you
examine the program and the output. Note
(1) This is a horrid program and should not be a model for anything you
will ever write, and
(2) The output reported below the program listing is for one
implementation. There is no way for me to predict what your
implementation will actually do with it.
#include <stdio.h>
int main(void)
{
/* note that 'char' may be either unsigned or signed */
unsigned char a = 0x91;
signed char b = 0x91; /* possible overflow */
unsigned int c;
signed int d;
printf
("note that each attempt to print an unsigned value using
\"%%x\"\n"
"is dodgy and should not, in fact, be done.\n\n");
printf("unsigned char a as (unsigned) hex = %x\n", a);
printf("signed char b as (unsigned) hex = %x\n\n", b);
c = a;
d = a;
printf
("unsigned int c and signed int d assigned (unsigned char) 0x91\n"
"unsigned int c as (unsigned) hex = %x\n"
"signed int d as (unsigned) hex = %x\n\n", c, d);
c = b;
d = b;
printf
("unsigned int c and signed int d assigned (signed char) 0x91\n"
"unsigned int c as (unsigned) hex = %x\n"
"signed int d as (unsigned) hex = %x\n\n", c, d);
return 0;
}
[output on one implementation]
note that each attempt to print an unsigned value using "%x"
is dodgy and should not, in fact, be done.
unsigned char a as (unsigned) hex = 91
signed char b as (unsigned) hex = ffffff91
unsigned int c and signed int d assigned (unsigned char) 0x91
unsigned int c as (unsigned) hex = 91
signed int d as (unsigned) hex = 91
unsigned int c and signed int d assigned (signed char) 0x91
unsigned int c as (unsigned) hex = ffffff91
signed int d as (unsigned) hex = ffffff91