开发者

C bits shifting short ints

Why result of

include <stdio.h>
int main()
开发者_Go百科{
    unsigned short int i = 0xff ;
    unsigned short int j;
    j= i<<2;
    printf("%x n%x\n", i, j);
    return 0;
}

is j = 3fc ?

if both i and j are short int - so they are 2bytes values, so j shouldnt =fc ??

thx in advance for explanations. ~

~


Shifting 0xff left two bits looks like this:

    0000 0000 1111 1111
       0    0    f    f

    0000 0011 1111 1100     -- Shifted left 2 bits.
       0    3    f    c

So 0x00ff << 2 = 0x03fc. Everything looks as it should be .


No, 0x3fc is correct. Note that a byte is two hex digits, so a (16-bit) short has a total of 4 hex digits.


0xff << 2 == 0xff * 4 == 0x3fc == 1020

Even if they are 2-bytes, they are allowed to hold this small value.


3FC requires only 12 bits to store so it can be stored in 2 bytes.


C++ makes no guarantee as to the number of bytes in an unsigned short int. It in fact makes almost no guarantee about the size of any type other than char which is guaranteed to be 1 byte.

In this case though it's irrelevant because 3fc can be successfully stored in only 2 bytes.


Maybe this is what you actually tried to write? (Remember an hex digit is 4 bits only, ie, half a byte)

#include <stdio.h>
int main()
{
    unsigned short int i = 0xffff;
    unsigned short int j;
    j = i<<8;
    printf("%x  %x\n", i, j);
    return 0;
}

This outputs ffff ff00

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜