Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# bitwise operations

Gabriele Gigliotti
Greenhorn

Joined: Jan 19, 2003
Posts: 5
Hello everybody,
I am a newcomer, I am preparing for SCJP, I have bought Kathy's book and I am doing some exercises other than that i found in the book...
this evening I found the following question on http://www.javaprepare.com/quests/operat_q.html
question number 11
What gets printed when the following program is compiled and run. Select the one correct answer.

and the right answer is H ??? why
here is the process I do in my mind, please tell me where is my fault!
1. a byte is 8 bit
2. a byte with value 3 has this bit rapresentation 00000011
3. now the complement operator ~ inverts all the bits, so that each 1 bit becomes 0, and each 0 bit becomes 1. If this is right I should obtain:
11111100 which is 252... am i right? or I missing something?
P.S.: please forgive my bad english... java is not the only language I have to learn
Ciao, Gabriele
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Gabriele,
One thing you overlooked is 11111100 has 1 on the MSB (sign bit) indicating it is a negative
number which is -4.

not so smart guy still curious to learn new stuff every now and then
Gabriele Gigliotti
Greenhorn

Joined: Jan 19, 2003
Posts: 5
Hello, Chi Lin
You are right I forgotten the meaning of the MSB but I still miss the answer
a byte with value -4 has maybe this bit rapresentation?
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
for 2's compliment, the formula to get the negative is

-x = ~x + 1 ,
let x be 4, the representation for -4 is then
~0000100 -> 11111011
+ 1 -> 00000001
--------------------------------
11111100,
PS :I have some problem to get the alignemt
right, hope it is OK this time .
[ January 31, 2003: Message edited by: chi Lin ]
Gabriele Gigliotti
Greenhorn

Joined: Jan 19, 2003
Posts: 5
chi Lin,