为什么用char数组进行按位运算会产生不同的结果?

时间:2018-12-02 12:42:36

标签: c bitwise-operators

有人可以告诉我为什么这两个陈述产生不同的结果吗? Java中的相同代码会产生完全相同的结果。我将在下面发布C和Java代码段。谢谢! :)

char src[] = { 'a', 'b', 'c' };
int sp0 = 0;
int bits = (src[sp0++] & 0xff) << 16 |
    (src[sp0++] & 0xff) << 8 |
    (src[sp0++] & 0xff);

printf("%d\n", bits);

bits = ('a' & 0xff) << 16 |
    ('b' & 0xff) << 8 |
    ('c' & 0xff);

printf("%d\n", bits);

输出:

6381921
6382179

Java中的相同代码(几乎完全相同):

    char src[] = {'a', 'b', 'c'};
    int sp0 = 0;
    int bits = (src[sp0++] & 0xff) << 16 |
            (src[sp0++] & 0xff) << 8 |
            (src[sp0++] & 0xff);

    System.out.println(bits);

    bits = ('a' & 0xff) << 16 |
            ('b' & 0xff) << 8 |
            ('c' & 0xff);

    System.out.println(bits);

输出:

6382179
6382179

编辑-----------

感谢重复的链接(如下)。在这种情况下,我需要跳过增量运算符:

char src[] = { 'a', 'b', 'c' };
int sp0 = 0;
int bits = (src[sp0] & 0xff) << 16 |
    (src[sp0 + 1] & 0xff) << 8 |
    (src[sp0 + 2] & 0xff);

printf("%d\n", bits);

bits = ('a' & 0xff) << 16 |
    ('b' & 0xff) << 8 |
    ('c' & 0xff);

printf("%d\n", bits);

0 个答案:

没有答案