JosiP
JosiP

Reputation: 225

C bits shifting short ints

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. ~
~

Upvotes: 1

Views: 1348

Answers (6)

Robert Cartaino
Robert Cartaino

Reputation: 28142

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 .

Upvotes: 5

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340486

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

Upvotes: 0

JaredPar
JaredPar

Reputation: 755557

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.

Upvotes: 0

Naveen
Naveen

Reputation: 73503

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

Upvotes: 1

dirkgently
dirkgently

Reputation: 111316

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

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

Upvotes: 1

James Curran
James Curran

Reputation: 103595

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

Upvotes: 4

Related Questions