programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# shift operators.. again

Ranch Hand
Posts: 1561
• Number of slices to send:
Optional 'thank-you' note:
just when I'm starting to feel confortable with shifting, there's my friend Dan with his excellent questions... :roll:

What is the result of attempting to compile and run the above program?
a. Prints: -4
b. Prints: -3
c. Prints: -2
d. Prints: 0
e. Prints: 1
f. Prints: 127
g. Prints: 508
h. Runtime Exception
i. Compiler Error
j. None of the Above
It prints -4. I reached til 508, but now this 508 int value has to be chopped off to fit in a byte, right? How do you guys do that?..

Ranch Hand
Posts: 74
• Number of slices to send:
Optional 'thank-you' note:
Hi Andres
You cannot consider this way, you must consider it as 8 bit number and the digits that go out from the left are lost. Then if the leftmost bit is 1 that means it is a negative number so you must calculate the two's complement of the number.

Hope that Helps
[ June 29, 2003: Message edited by: Alexan Kahkejian ]

Andres Gonzalez
Ranch Hand
Posts: 1561
• Number of slices to send:
Optional 'thank-you' note:
Thanks Alexan. What I usually do is the following:
x >> n = x / 2^n
x << n = x * 2^n
and that's it. Using this formula I got 508. So from this number, I didn't know how to "make it fit" into a byte.

Ranch Hand
Posts: 1392
• Number of slices to send:
Optional 'thank-you' note:
b <<= 2 is the same as b = (byte)(b << 2)
except that b is evaluated only once.
Let�s evaluate this expression: (byte)(b << 2)
First the left operand b is promoted to type int.
01111111 is promoted to 0000 0000 0000 0000 0000 0000 0111 1111
Then the left shift operation << is performed.
0000 0000 0000 0000 0000 0001 1111 1100 (== 508)
Then the result is converted from type int to type byte by
discarding all but the 8 lowest order bits.
11111100 (== -4)
[ June 29, 2003: Message edited by: Marlene Miller ]

Marlene Miller
Ranch Hand
Posts: 1392
• Number of slices to send:
Optional 'thank-you' note:
b = b << 2; //compiler error, must be cast to type byte
b <<= 2; //implicit cast to type byte
In both of these examples, the value of b is promoted to an int before << is performed.

Ranch Hand
Posts: 151
• Number of slices to send:
Optional 'thank-you' note:
I think we need to do like this.. keep subtracting 128 from 508 till you get a nearest value to -128 in range (-128 & 127). Can anyone confirm whether this is correct way?
Thanks,