• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bytes in Java

 
Sarojini Venky
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
This must seem extremely silly and less than basic!!! But seriously how does an int get stored in a byte data type. How does the truncation happen?
What info I have is that it divides the int(if > than 256) by 256 and stores the remainder in the byte. But what happens if I want to store a value 250?
Would be very much obliged if anyone could help me.
Thanks
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to Java in General Begginners.
 
Eddie Vanda
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Output is: i=250 b=-6
In two's complement notation used for an int, each column has a weighting of an increasing power of two, starting from the least significant bit. However, the most significant bit has a minus sign in front of its weighting.
So for the least significant 8 bits the weightings are
128, 64, 32, 16, 8, 4, 2 and 1 (8 bits)
And the representation of 250 puts 1's into these columns:
250 = 128 + 64 + 32 + 16 + 8 + 2
Now when you transfer these 8 bits into a 2's complement byte, the weightings are:
-128, 64, 32, 16, 8, 4, 2 and 1 (8 bits)
so the bit pattern for 250 in an int becomes -6
-6 = -128 + 64 + 32 + 16 + 8 + 2
Ed
Hope that is not too complicated!
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so in other words: you may not store a 250 in a byte.
bytes may be from -128...127.
 
Sarojini Venky
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic