File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes bytes in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "bytes in Java" Watch "bytes in Java" New topic

bytes in Java

Sarojini Venky

Joined: Apr 26, 2004
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.
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Moving this to Java in General Begginners.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Eddie Vanda
Ranch Hand

Joined: Mar 18, 2003
Posts: 281

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
Hope that is not too complicated!

The nice thing about Standards is that there are so many to choose from!
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

so in other words: you may not store a 250 in a byte.
bytes may be from -128...127.
Sarojini Venky

Joined: Apr 26, 2004
Posts: 3
Thanks everyone!!!
I agree. Here's the link:
subject: bytes in Java
It's not a secret anymore!