tags:

views:

65

answers:

7

Hi

Why result of

include <stdio.h>
int main()
{
    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. ~
~

+4  A: 

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

James Curran
+1  A: 
0xff << 2 == 0xff * 4 == 0x3fc == 1020

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

dirkgently
+1  A: 

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

Naveen
even 10 bits are sufficient..but if we keep a hex digit as 4 bits then 12..
Naveen
A: 

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.

JaredPar
A: 

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

Vinko Vrsalovic
+4  A: 

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 .

Robert Cartaino
A: 

of course ! me stupid ! :) thx

JosiP
that should be a comment :-) not answer..
Naveen