• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

byte shift

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class EBH005 {
public static void main (String[] s) {
byte b = 127; b <<= 2;System.out.println(b);
}}

What is the result of attempting to compile and run the program?

a. Prints: -4
b. Prints: -3
c. Prints: -2
d. Prints: 0
e. Prints: 1
f. Prints: 127
g. Prints: 508
h. Run-time error
i. Compile-time error
j. None of the above

The answer to above ? is a. Can anybody exaplin me that ? The answer is -4 and I didnot get how 11111100 is converted to -4 ? I know, its two's complement...but still can anybody elaborate it further ?
 
Ranch Hand
Posts: 657
Spring VI Editor Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I did not get how 11111100 is converted to -4?


The leftmost bit indicates the sign (negative, in this case). Flip the bits and add 1.

Flipped: 00000011
Add 1: 00000100

Read the last number as binary and remember the sign. Ergo, -4.

Hope this helps.
 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yatikashipurut,

The answer is in your question. 11111100 is the 2's compliment of -4. Here's how it works:

In order to get a negative number in binary using 2's compliment, you flip all the bits and add one. So,

00000100 => 4

11111011 => flip all the bits
00000001 => add one
---------
11111100 => -4

Do the same process again to go back to +4.

11111100 => -4

00000011 => flip all the bits
00000001 => add one
---------
00000100 => 4
[ August 25, 2005: Message edited by: Ryan Kade ]
 
Be reasonable. You can't destroy everything. Where would you sit? How would you read a tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic