programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# bytes in Java

Sarojini Venky
Greenhorn
Posts: 3
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
Moving this to Java in General Begginners.

Eddie Vanda
Ranch Hand
Posts: 283

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
so in other words: you may not store a 250 in a byte.
bytes may be from -128...127.

Sarojini Venky
Greenhorn
Posts: 3
Thanks everyone!!!