-1

I defined a struct named queryData like the code below. When I tried to using shift and right operation to operate and assign a data, qdata.data.data4[0], printing the data out, there is something wrong that the data I stated before is a char which is 8 bits, but when I print it it actually 32 bits,0xffffff8b. I wonder how it could be like this. Thank you.

int main(void){
    union Data{
        char data2[2];
        char data4[4];
    };
    struct queryData{
        char byte; // 2bytes or 4bytes.
        union Data data;
    };
    struct queryData qdata;
    unsigned long int data;
    data = rand()%4294967295;
    qdata.byte = 4;
    qdata.data.data4[0] = (char)(data>>24);
    qdata.data.data4[1] = (char)((data<<8)>>24);
    qdata.data.data4[2] = (char)((data<<16)>>24);
    qdata.data.data4[3] = (char)((data<<24)>>24);
    printf("%ld\n",data);
    printf("%x\n",qdata.data.data4[0]);
    printf("%x\n",qdata.data.data4[1]);
    printf("%x\n",qdata.data.data4[2]);
    printf("%x\n",qdata.data.data4[3]);
    printf("%x",(unsigned int)(1804289383<<8)>>24); 
    return EXIT_SUCCESS;
}

The result is below: The result after run

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
Franco
  • 123
  • 11

2 Answers2

1

You are using the wrong printf format. Use %hhd for char as a numerical value. If you'd prefer to print it in hex, you'd have to use unsigned char as a type, instead of char.

What you are observing is that your char is promoted to int and passed as such to printf. You then print that int as an unsigned in hex. Because your platform seems to have a signed char type and uses two's complement for negative values, you see the pattern with all the starting bits switched to on.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

Vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since 8b have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

To avoid such promotion you have to use length specifier in printf:

printf("%hhx\n",qdata.data.data4[1]);