• Post Reply Bookmark Topic Watch Topic
  • New Topic

8-Bit problem  RSS feed

 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Readers,
I recently read about 8-bits in JavaRanch Campfire Story. According to there, when left-shift assignment is performed then the bits are shifted to the left according to the number specified.
But when I printed the value of 1<<9 I get 512 or something like that. But according to what I learnt it [i]should be 2[/b]. Please can anyone explain to me why this is happening.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Literals such as 1 or 9 are interpreted by Java as int literals, which are 32-bit values (i.e., 9 is not enough to make it "wrap").
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A integer 1 decimal is represented in binary as:

0000 0000 0000 0000 0000 0000 0000 0001

Shift it to the left 9 times you get:

0000 0000 0000 0000 0000 0010 0000 0000

Which translates to 512 in decimal.

Henry
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Readers,
Forgive my ignorance but what are int literals?
 
Ryan McGuire
Ranch Hand
Posts: 1143
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you basically understand what an int is. The one new detail that was mentioned above is that an int is 32 bits long.

A 'literal' is a hardcoded value right in the source code. For instance, in...



...the 41, 'S', 'h', 'y', 'a', 'm', and "Murarka" are all literals. 41 is an int literal; 'S' through 'm' are char literals, and "Murarka" is a String literal.

It might get a little tricky. In...


... 12 is a int literal getting assigned to a long variable. It will automatically get 'promoted' to long as part of the assignment. To designate a long literal, append an 'L' or 'l' to the number, as with the 13 above. (I prefer the capital 'L' so that it doesn't get confused with a '1' digit. Compare "myLong=131;" and "myLong=13l;".)

There are of course more types of literals, but I think you get the basic idea.

Cool?

Ryan
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Ryan,
Thank you very much for spending your precious time in teaching those small things to a duddo like me.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!