在这种情况下,unsigned char和unsigned short之间有什么区别?

时间:2012-10-12 07:22:03

标签: c bit-manipulation

我们需要将使用unsigned char作为位掩码的程序升级到使用unsigned short作为位掩码的较新版本。我相信它们之间存在一些差异,因为我们的程序使用相同的逻辑与unsigned char失败变为unsigned short。 (这是我们购买的外部库。库已升级,所以我们也需要更改程序。)

Old version:
typedef struct SomeStruct {
    unsigned char   bit_mask;
#       define      SomeStruct_a_present 0x80
#       define      SomeStruct_b_present 0x40
#       define      SomeStruct_c_present 0x20
    X          x;
    Y          y;
    A          a;  /* optional; set in bit_mask
                                * SomeStruct_a_present if
                                * present */

    B          b;  /* optional; set in bit_mask
                                * SomeStruct_b_present if
                                * present */

    C          c;  /* optional; set in bit_mask
                                * SomeStruct_c_present if
                                * present */
} SomeStruct;



New version:
typedef struct SomeStruct {
    unsigned short   bit_mask;
#       define      SomeStruct_x_present 0x8000
#       define      SomeStruct_y_present 0x4000
#       define      SomeStruct_a_present 0x2000
#       define      SomeStruct_b_present 0x1000
#       define      SomeStruct_c_present 0x0800
    X          x;/* optional; set in bit_mask
                                * SomeStruct_x_present if
                                * present */
    Y          y;/* optional; set in bit_mask
                                * SomeStruct_y_present if
                                * present */
    A          a;  /* optional; set in bit_mask
                                * SomeStruct_a_present if
                                * present */

    B          b;  /* optional; set in bit_mask
                                * SomeStruct_b_present if
                                * present */

    C          c;  /* optional; set in bit_mask
                                * SomeStruct_c_present if
                                * present */
} SomeStruct;

我认为当前行存在一些问题,因为程序崩溃:

我们当前设置bit_mask的方法:

someStruct.bit_mask = SomeStruct_a_present;
someStruct.bit_mask |= SomeStruct_b_present;
someStruct.bit_mask |= SomeStruct_c_present;

4 个答案:

答案 0 :(得分:5)

用无符号短接此行

someStruct.bit_mask = SomeStruct_a_present;

会将位掩码的值设置为8192,但使用unsigned char时,该值将设置为128

原因:

unsigned short是2个字节长,位掩码是00100000000000000x2000)但是对于unsigned char,这个值将是100000000x80)。

答案 1 :(得分:3)

 I believe there is some difference between( unsigned short and unsigned char)

sizeof(unsigned char)= 1个字节。

sizeof(unsigned short)= 2个字节。

答案 2 :(得分:1)

“unsigned char”的长度为1 Byte,“unsigned short”的长度为2

答案 3 :(得分:0)

MODIFIERS 部分下的here链接,您可以看到,

sizeof(unsigned char)= 1 Byte and Range = 0 - > 255。

sizeof(无符号短整数)= 2字节和范围= 0 - > 65535

Ideone Output