small query on bitwise shift right operator

N

nirmalr

Hi all,

int
main()
{
unsigned char j = 0;

j = ~j >> 1;
printf("%u\n", j);
return 0;
}

I am expecting that the above program will print "128" as output,
Because I am negating "j" and right shifting it once.

But When I run this program, I am getting "255" as output.

Can any of you explain the reason for this or please forward me to
correct FAQ.

Thanks,
Nirmal R.
 
G

Giorgio Silvestri

Hi all,

int
main()
{
unsigned char j = 0;

j = ~j >> 1;
printf("%u\n", j);
return 0;
}

I am expecting that the above program will print "128" as output,
Because I am negating "j" and right shifting it once.

But When I run this program, I am getting "255" as output.

to 'j' the integer-promotion is applied before executing ~.
 
S

spibou

I cannot imagine how you came up with 128. You
were guaranteed to get an odd number as a result
even disregarding integer promotion. You start with
a number which is 0. Then you apply ~ which will
make all bits 1 and in particular the bit next to the
LS (Least Significant) one. So when you shift to right
that bit now becomes the LS. Since this bit is 1 the
number will be odd so definitely not 128.
to 'j' the integer-promotion is applied before executing ~.

Spiros Bousbouras
 
N

nirmalr

I cannot imagine how you came up with 128. You
were guaranteed to get an odd number as a result
even disregarding integer promotion. You start with
a number which is 0. Then you apply ~ which will
make all bits 1 and in particular the bit next to the
LS (Least Significant) one. So when you shift to right
that bit now becomes the LS. Since this bit is 1 the
number will be odd so definitely not 128.


Spiros Bousbouras

I am sorry, yes it suppose to print an odd number (127).

The program works fine If I do type casting as suggested by "Giorgio
Silvestri".

int
main()
{
unsigned char j = 0;

j = ((unsigned char) ~j) >> 1;
printf("%u\n", j);
return 0;
}

Thanks a lot,
Nirmal R.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top