已知

  1. int 4 bytes = 32 bits, char 1 byte = 8bits

  2. 負數以2's complement 儲存

  3. %d是signed integer %u是unsigned integer。做型別轉換時,需要做sign extention,方式為不足的bit補其符號(即正補0,負補1)。

環境

32 bits x86 platform

code

printf("%d %u\n", i);

case

1. int i = -1=10000000 00000000 00000000 00000001

           2's=>11111111 11111111 11111111 11111111

    results: -1 4294967295(0xffff)

2. unsigned int i = -1=10000000 00000000 00000000 00000001

                         2's=>11111111 11111111 11111111 11111111

    results: -1 4294967295(0xffffffff)

3. char i = -1= 10000001

              2's=>11111111

     sign extention ==>11111111 11111111 11111111 11111111

     results: -1 4294967295(0xffffffff)

4. unsigned char i = -1 = 10000001

                              2's=>11111111

     sign extention ==>00000000 00000000 00000000 11111111

     results: 255 255

5. char i =-128 = 10000000

                  2's=>10000000

     sign extention ==> 11111111 11111111 11111111 10000000

     results: -128 4294967168(0xffffff80)

6. unsigned char i = -128 = 10000000

                                  2's=>10000000

     sign extention ==> 00000000 00000000 00000000 10000000

     results: 128 128

kezeodsnx 發表在 痞客邦 PIXNET 留言(0) 人氣()